package com.alibaba.citrus.cr.unified.inventory.repository.impl;

import com.alibaba.citrus.cr.common.lock.RedisLock;
import com.alibaba.citrus.cr.unified.inventory.contants.FeaturesKey;
import com.alibaba.citrus.cr.unified.inventory.model.AllocateApplyOrderDeliveredRequest;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateApplyOrderWriteRepository;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateOrderReadRepository;
import com.alibaba.citrus.cr.common.annotation.EpochTransactional;
import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.log.ModuleEnum;
import com.alibaba.citrus.cr.common.util.JsonUtil;
import com.alibaba.citrus.cr.common.util.NameUtil;
import com.alibaba.citrus.cr.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.citrus.cr.common.util.TimeUtil;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateApplyOrderDetailReadRepository;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateOrderWriteRepository;
import com.alibaba.citrus.cr.unified.inventory.utils.CodeUtil;
import com.alibaba.citrus.cr.unified.inventory.utils.DateUtils;
import com.alibaba.citrus.cr.unified.inventory.utils.InfoUtil;
import com.alibaba.cloud.retail.delivery.api.model.delivery.enums.FulfillmentDirectionTypeEnum;
import com.alibaba.cloud.retail.delivery.api.model.delivery.response.fulfillment.FulfillmentGetRes;
import com.alibaba.cloud.retail.delivery.api.model.fulfillment.request.SearchFulfullmentOrderReq;
import com.alibaba.cloud.retail.delivery.api.service.bcfulfillment.FulfillmentOrderAbilityService;
import com.alibaba.cloud.retail.wms.api.model.orders.common.WarehousingOrderDTO;
import com.alibaba.cloud.retail.wms.api.model.orders.common.WmsOrderDetailDTO;
import com.alibaba.cloud.retail.wms.api.model.orders.request.WmsOrderQueryRequest;
import com.alibaba.cloud.retail.wms.api.model.orders.response.WarehousingOrdersQueryResponse;
import com.alibaba.cloud.retail.wms.api.service.orders.WarehousingOrderReadService;
import com.alibaba.cz.base.model.enterprise.EmployeeSDO;
import com.alibaba.cz.base.model.promotion.util.DateUtil;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.log.model.OpLogModel;
import com.alibaba.cz.base.tool.log.model.OperatorType;
import com.alibaba.cz.enterprise.api.model.employee.EmployeeResponse;
import com.alibaba.cz.enterprise.api.service.EmployeeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.user.dto.LoginUser;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationById2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIds2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIds2Response;
import com.epoch.app.bcorder.model.dto.BatchQueryWarehouseByIdsRequest;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryByIdsRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.model.dto.GetDownOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAddressListRequest;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAddressListResponse;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.dto.QueryDeliveryWarehouseByTypeRequest;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.dto.QueryReceivingWarehouseByTypeRequest;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.crunifiedinventory.consignmentorder.model.ConsignmentOrder;
import com.epoch.app.crunifiedinventory.consignmentorder.service.ConsignmentOrderService;
import com.epoch.app.crunifiedinventory.consignmentorderline.model.ConsignmentOrderLine;
import com.epoch.app.crunifiedinventory.consignmentorderline.service.ConsignmentOrderLineService;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.dto.AllocateApplyOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.dto.LoadAllocateApplyOrderRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.model.AllocateApplyOrder;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.service.AllocateApplyOrderService;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.dto.AllocateApplyOrderDetailLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.dto.UpdateAllocateApplyOrderDetailResponse;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.dto.UpdateFeaturesRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.model.AllocateApplyOrderDetail;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.service.AllocateApplyOrderDetailService;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.AllocateOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.CreateAllocateOrderResponse;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.LoadAllocateOrderRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.UpdateAllocateOrderResponse;
import com.epoch.app.crunifiedinventory.domain.allocateorder.model.AllocateOrder;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.dto.*;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.model.AllocateOrderDetail;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.service.AllocateOrderDetailService;
import com.epoch.app.crunifiedinventory.dto.request.*;
import com.epoch.app.crunifiedinventory.dto.response.*;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelDeliveredRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelDeliveredResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelReceivedRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelReceivedResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelShippedRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelShippedResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCancelShippedScItemDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCreateRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderDeliveryRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderGetInOutOrderRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderReturnOrderRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderReturnOrderResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderScItemDetail;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderScItemDetailDTO;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderLineLoadListRequest;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.model.dto.GetListOutinForAllocationResponse;
import com.epoch.app.crunifiedinventory.model.dto.GetListWarehouseStock2Request;
import com.epoch.app.crunifiedinventory.model.dto.UpdateAllocateApplyOrderBySapSyncRequest;
import com.epoch.app.crunifiedinventory.model.dto.UpdateAllocateApplyOrderBySapSyncScItemDetail;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInventory;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInventoryDoms;
import com.epoch.app.crunifiedinventory.model.dto.WmsSDO;
import com.epoch.app.crunifiedinventory.model.enums.AllocateApplyOrderOperationTypeEnum;
import com.epoch.app.crunifiedinventory.model.enums.AllocateOrderStatus;
import com.epoch.app.crunifiedinventory.model.enums.CreditCheck;
import com.epoch.app.crunifiedinventory.model.enums.CreditCheckStatus;
import com.epoch.app.crunifiedinventory.model.enums.WmsStatusEnum;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderDetailSDO;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderSDO;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderWithOrderDetailsSDO;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateApplyOrderStatusEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateStatusEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.DocumentReasonEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.DocumentTypeEnum;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: yuhw
 * @date: 2021年09月17日 11:26
 **/
@Component
public class AllocateOrderWriteRepositoryImpl implements AllocateOrderWriteRepository {

    private final static Log log = Log.getLogger(AllocateOrderWriteRepositoryImpl.class);

    @Resource
    AllocateOrderService allocateOrderService;
    @Resource
    AllocateOrderDetailService allocateOrderDetailService;
    @Resource
    AllocateApplyOrderService allocateApplyOrderService;
    @Resource
    AllocateOrderReadRepository allocateOrderReadRepository;
    @Resource
    EpochLoginUserService epochLoginUserService;

    @Autowired
    CrPlatformEnhanceService otsPlatformEnhanceService;

    @Resource
    UnifiedInventoryService unifiedInventoryService;
    @Resource
    AllocateApplyOrderDetailService allocateApplyOrderDetailService;
    @Resource
    ConsignmentOrderService consignmentOrderService;
    @Resource
    ConsignmentOrderLineService consignmentOrderLineService;
    @Resource
    AllocateApplyOrderDetailReadRepository allocateApplyOrderDetailReadRepository;

    @Resource
    CustomerAddressService customerAddressService;


    @Resource
    private ForecastWarehouseService forecastWarehouseService;

    @Resource
    BaseDataService baseDataService;
    @Resource
    CrUnifiedInventoryService otsUnifiedInventoryService;
    @Resource
    private AllocateApplyOrderWriteRepository allocateApplyOrderWriteRepository;
    @DubboReference
    private EmployeeService employeeService;
    @DubboReference
    private FulfillmentOrderAbilityService fulfillmentOrderAbilityService;
    @DubboReference
    private WarehousingOrderReadService warehousingOrderReadService;

    private static final Integer MAX_PAGE_SIZE = 1000;
    private static final String SC_ITEM_PRODUCT_GROUP_CODE = "11";
    private static final String PIRFCUSER = "PIRFCUSER";
    private static final Integer NORMAL = 1;


    public static String getOrderReason(String orderReasonCode) {
        for (DocumentReasonEnum reason : DocumentReasonEnum.values()) {
            if (Objects.equals(reason.getCode(), orderReasonCode)) {
                return reason.getDesc();
            }
        }
        return null;
    }

    public static String getTypeDesc(Integer type) {
        for (AllocateOrderTypeEnum typeEnum : AllocateOrderTypeEnum.values()) {
            if (Objects.equals(typeEnum.getType(), type)) {
                return typeEnum.getDesc();
            }
        }
        return null;
    }

    /**
     * 同步更新 008 TODO 待更新
     *
     * @return
     */
    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public AllocateOrderSyncResponse passiveSync(AllocateOrderSyncRequest allocateOrderSyncRequest) {
        //先检验下参数情况
        AllocateOrderSyncResponse response = new AllocateOrderSyncResponse();
        if (allocateOrderSyncRequest == null) {
            response.setCode("请求参数不能为空");
            return response;
        }
        if (CollectionUtils.isEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            response.setCode("物料不能为空");
            return response;
        }
        List<String> collect = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode())).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            response.setCode("物料不能为空");
            return response;
        }
        //22.04.25 电商调拨单行不能重复
        WmsSDO wmsSDO = InfoUtil.getWmsSDO(allocateOrderSyncRequest.getReceiveAreaId());
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(wmsSDO.getSapSalesOrgId());
        if (isECommerceOrder){
            Set<String> outAllocateOrderLineIdSet = allocateOrderSyncRequest.getAllocateOrderScItemDetails()
                .stream().map(AllocateOrderScItemDetailDTO::getOutAllocateOrderLineId).collect(Collectors.toSet());
            if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > outAllocateOrderLineIdSet.size()){
                response.setCode("外部调拨单行号不能重复");
                return response;
            }
        }else {
            if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > collect.size()) {
                response.setCode("物料不能重复");
                return response;
            }
        }

        //找出预报单
        AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
        if (!StringUtils.isAllBlank(allocateOrderSyncRequest.getAllocateApplyOrderCode(),
                allocateOrderSyncRequest.getOutAllocateApplyOrderId())) {
            AllocateApplyOrderLoadListRequest applyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getAllocateApplyOrderCode())){
                applyOrderLoadListRequest.setCode(allocateOrderSyncRequest.getAllocateApplyOrderCode());
            }
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getOutAllocateApplyOrderId())){
                applyOrderLoadListRequest.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
            }
            Result<List<AllocateApplyOrder>> applyResult = allocateApplyOrderService.loadAllocateApplyOrderList(applyOrderLoadListRequest);
            if (applyResult != null && CollectionUtils.isNotEmpty(applyResult.getResult())) {
                allocateApplyOrder = applyResult.getResult().get(0);
                if (AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrder.getStatus())) {
                    response.setCode("预报单是待推送状态,不允许同步");
                    return response;
                }
            }
        }
        AllocateOrderLoadListRequest queryRequest = new AllocateOrderLoadListRequest();
        queryRequest.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
        queryRequest.setCode(allocateOrderSyncRequest.getCode());
        Result<List<AllocateOrder>> queryResult = allocateOrderService.loadAllocateOrderList(queryRequest);
        if (queryResult != null && CollectionUtils.isNotEmpty(queryResult.getResult())) {
            allocateOrderSyncRequest.setCode(queryResult.getResult().get(0).getCode());
        }

        String code = allocateOrderSyncRequest.getCode();
        if (StringUtils.isBlank(code)) {
            AllocateOrderLoadListRequest orderLoadListRequest = new AllocateOrderLoadListRequest();
            orderLoadListRequest.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
            Result<List<AllocateOrder>> orderListResult = allocateOrderService.loadAllocateOrderList(orderLoadListRequest);
            if (orderListResult != null && CollectionUtils.isNotEmpty(orderListResult.getResult())) {
                response.setCode("该外部单号已经存在,不允许新增");
                return response;
            }
            code = CodeUtil.planCode();
            //新增调拨单
            AllocateOrder allocateOrder = JsonUtil.convert(allocateOrderSyncRequest, AllocateOrder.class);
            //代表是常温产品
            allocateOrder.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
            allocateOrder.setCode(code);
            allocateOrder.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
            allocateOrder.setAllocateApplyOrderCode(StringUtils.isBlank(allocateApplyOrder.getCode()) ? null : allocateApplyOrder.getCode());
            if (allocateApplyOrder.getType() != null) {
                allocateOrder.setType(allocateApplyOrder.getType());
            }
            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司 代码在下面
            allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
            //如果收货仓不是空的.
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getReceiveAreaId())) {
                allocateOrder.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
            } else {
                allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId() == null ? null :
                        allocateApplyOrder.getReceiveWarehouseId() + "");
            }
            allocateOrder.setIsDTC(allocateApplyOrder.getIsDTC() != null && allocateApplyOrder.getIsDTC());
            allocateOrder.setSapSalesOrgId(allocateApplyOrder.getHeadquartersOrganizationCode());
            //如果出入库仓改变的话, 更新一下.
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
            allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
            allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
            WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());
            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
            allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
            if (allocateApplyOrder.getApplyOrgId() == null && StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
//                GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//                getOrganiztionByIdRequest.setId(allocateOrder.getReceiveOrgId());
//                OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//                if(organiztionById != null){
//                    allocateOrder.setApplyOrgId(organiztionById.getParentId());
//                }
                OrganizationSDO orgSDO = getOrgSDO(allocateOrder.getReceiveOrgId());
                if (orgSDO != null){
                    allocateOrder.setApplyOrgId(orgSDO.getParentId());
                }
            }
            allocateOrder.setConfirmTime(new Date());
            if (allocateOrderSyncRequest.getDocDate() == null) {
                allocateOrder.setDocDate(InfoUtil.docDate());
            } else {
                allocateOrder.setDocDate(allocateOrderSyncRequest.getDocDate());
            }
            //如果是全关闭 那就标记为关闭
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                boolean allClosed = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                        .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
                if (allClosed) {
                    allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
                } else {
                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                }
            }
            //成本中心 客户采购参考号 -- 008 更新时 客户成本中心不传递 客户采购参考号
            allocateOrder.setSapCostCenter(allocateApplyOrder.getSapCostCenter());
            allocateOrder.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
            allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
            CreateAllocateOrderResponse createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                int i = 1;
                //用来更新
                List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
                for (AllocateOrderScItemDetailDTO scItemDetail : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
                    AllocateOrderDetail detail = JsonUtil.convert(scItemDetail, AllocateOrderDetail.class);
                    detail.setAllocateOrderCode(code);
                    detail.setAllocateOrderId(createAllocateOrderResponse.getLastInsertId());
                    detail.setType(AllocateOrderTypeEnum.PLAN.getType());
                    detail.setAllocateApplyOrderLineId(scItemDetail.getAllocateApplyOrderLineId());
                    //商品转换 需要把sap的转换成我们的
                    String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetail.getScItemCode());
                    //如果货品查询失败返回
                    if (StringUtils.isBlank(scItemId)){
                        log.error("AllocateOrderWriteRepositoryImpl_passiveSync_queryScItemIdError:{},request:{}",scItemDetail.getScItemCode(),JSON.toJSONString(allocateOrderSyncRequest));
                        response.setCode(scItemDetail.getScItemCode() +"货品查询不存在");
                        return response;
                    }
//                    detail.setScItemId(InfoUtil.deleteZeroPrefix(scItemDetail.getScItemCode()));
                    detail.setScItemId(scItemId);
//                    detail.setScItemCode(InfoUtil.deleteZeroPrefix(scItemDetail.getScItemCode()));
                    detail.setScItemCode(InfoUtil.subStringScItmCode(scItemDetail.getScItemCode()));
                    detail.setClose(scItemDetail.getClosed());
                    detail.setStatus(Objects.equals(scItemDetail.getClosed(), Boolean.TRUE) ?
                            AllocateOrderStatus.CLOSED.getValue() : AllocateOrderStatus.Shipment_Processing.getValue());
                    detail.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
                    detail.setReturnOrder(allocateOrder.getReturnOrder());
                    detail.setLineNo(i);
                    detail.setQuantity(InfoUtil.trim(detail.getQuantity()));
                    detail.setPrice(InfoUtil.trim(detail.getPrice()));
                    handleConfirmTime(detail, scItemDetail);
                    detail.setConfirmQuantity(InfoUtil.trim(scItemDetail.getConfirmQuantity()));
                    detail.setDiscountAmount(InfoUtil.trim(scItemDetail.getSubTotalAmount()));
                    detail.setSubTotalAmount(InfoUtil.trim(scItemDetail.getSubTotalAmount()));

                    allocateOrderDetailService.createAllocateOrderDetail(detail);
                    i++;
                    // 操作 预报单部分 回复数量 关闭状态 生产日期
                    //组装同步更新预报单的明细数据
                    syncScItemDetails.add(convert2SyncScItemDetail(detail,true,false,
                            scItemDetail.getCloseCode(), null,null));
                }
                //更改预报单主子单状态,回复数量 拒接原因...
                syncReplyAllocateApplyOrder(allocateApplyOrder,allocateOrder.getCode(),syncScItemDetails);
            }
//            delivery(allocateOrderSyncRequest.getOutAllocateOrderId());
            response.setCode(code);
            return response;
        }
        //下面是更新操作的操作
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setCode(allocateOrderSyncRequest.getCode());
        Result<List<AllocateOrder>> orderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (orderList == null || CollectionUtils.isEmpty(orderList.getResult())) {
            response.setCode("未查询到该调拨单号");
            return response;
        }

        AllocateOrder order = orderList.getResult().get(0);
        //如果

//        if (!Objects.equals(order.getOutAllocateOrderId(),allocateOrderSyncRequest.getOutAllocateOrderId())){
//            response.setCode("调拨单号和外部调拨单号关系不匹配");
//            return response;
//        }
        //如果是008传递过来是待推送,我们就直接先改成待发货状态
        if (Objects.equals(order.getStatus(), AllocateOrderStatus.WAIT_PUSH.getValue())) {
            order.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getOutAllocateOrderId())){
                order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
            }
            allocateOrderService.updateAllocateOrder(order);
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderId(order.getId());
            allocateOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
                for (AllocateOrderDetail detail : result.getResult()) {
                    //如果是待推送状态,就修改子单明细的状态
                    if (AllocateOrderStatus.WAIT_PUSH.getValue().equals(detail.getStatus())){
                        detail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        allocateOrderDetailService.updateAllocateOrderDetail(detail);
                    }
                }
            }
//            response.setCode("调拨单未推送成功或回调失败,不允许更新");
//            return response;
        }


        AllocateOrderDetailLoadListRequest checkRequest = new AllocateOrderDetailLoadListRequest();
        checkRequest.setAllocateOrderId(order.getId());
        checkRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> checkResult = allocateOrderDetailService.loadAllocateOrderDetailList(checkRequest);
        if (checkResult != null && CollectionUtils.isNotEmpty(checkResult.getResult()) && !isECommerceOrder) {
            //找出现有的明细; 如果传递的商品有新增的.
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                List<String> scItemCodes = checkResult.getResult().stream()
                        .filter(y -> StringUtils.isNotBlank(y.getScItemCode()))
                        .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode()))
                        .distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(scItemCodes)) {
                    List<String> list = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                            .map(z -> InfoUtil.subStringScItmCode(z.getScItemCode())).collect(Collectors.toList());
                    boolean b = scItemCodes.stream().anyMatch(x -> !list.contains(x));
                    if (b) {
                        response.setCode("物料编码不允许修改");
                        return response;
                    }
                }
            }
        }


        order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
        order.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
        order.setTypeCard(allocateOrderSyncRequest.getTypeCard());
        order.setSapChannel(allocateOrderSyncRequest.getSapChannel());
        order.setProductGroup(allocateOrderSyncRequest.getProductGroup());
        order.setShipAreaId(allocateOrderSyncRequest.getShipAreaId());
        order.setShipWarehouseId(allocateOrderSyncRequest.getShipWarehouseId());
        //如果有收货仓改变
        if (StringUtils.isNotBlank(allocateOrderSyncRequest.getReceiveAreaId())) {
            order.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
        }
        order.setReceiveWarehouseId(allocateOrderSyncRequest.getReceiveWarehouseId());
        order.setCreateTime(allocateOrderSyncRequest.getCreateTime());
        order.setShipMethod(allocateOrderSyncRequest.getShipMethod());
        order.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
        order.setFeatures(allocateOrderSyncRequest.getFeatures());
        order.setRemark(allocateOrderSyncRequest.getRemark());
        //如果出入库仓改变的话, 更新一下.
        WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(order.getShipAreaId());
        order.setShipWarehouseId(shipWmsSDO.getWarehouseId());
        order.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(order.getReceiveAreaId());
        order.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
        order.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
        if (allocateOrderSyncRequest.getDocDate() == null) {
            order.setDocDate(InfoUtil.docDate());
        } else {
            order.setDocDate(allocateOrderSyncRequest.getDocDate());
        }
        order.setGmt_modified(new Date());
        //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
        if (allocateApplyOrder.getApplyOrgId() == null && StringUtils.isNotBlank(order.getReceiveOrgId())){
//            GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//            getOrganiztionByIdRequest.setId(order.getReceiveOrgId());
//            OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//            if(organiztionById != null){
//                order.setApplyOrgId(organiztionById.getParentId());
//            }
            OrganizationSDO orgSDO = getOrgSDO(order.getReceiveOrgId());
            if (orgSDO != null){
                order.setApplyOrgId(orgSDO.getParentId());
            }
        }
        order.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
        if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            boolean allClosed = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                    .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
            if (allClosed) {
                order.setStatus(AllocateOrderStatus.CLOSED.getValue());
            } else {
                if (order.getStatus() == null) {
                    order.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                }
            }
        }
        // 参考号 和成本中心
        order.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
        order.setSapCostCenter(allocateApplyOrder.getSapCostCenter());
        order.setExpectedDeliveryDate(allocateOrderSyncRequest.getExpectedDeliveryDate());
        if (StringUtils.isBlank(order.getAllocateApplyOrderId()) && allocateApplyOrder.getId() != null){
            order.setAllocateApplyOrderId(allocateApplyOrder.getId().toString());
        }
        if (StringUtils.isBlank(order.getAllocateApplyOrderCode()) && StringUtils.isNotBlank(allocateApplyOrder.getCode())){
            order.setAllocateApplyOrderCode(allocateApplyOrder.getCode());
        }
        allocateOrderService.updateAllocateOrder(order);

        if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            //获取最大的行号
            AllocateOrderDetailLoadListRequest request = new AllocateOrderDetailLoadListRequest();
            request.setAllocateOrderCode(code);
            request.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> rr = allocateOrderDetailService.loadAllocateOrderDetailList(request);
            int line = 1;
            if (rr != null && CollectionUtils.isNotEmpty(rr.getResult())) {
//                String lines = rr.getResult().stream().filter(Objects::nonNull).filter(orderDetail -> StringUtils.isNotBlank(orderDetail.getLineNo()))
//                        .max(Comparator.comparing(AllocateOrderDetail::getLineNo)).get().getLineNo();
//                if (StringUtils.isNotBlank(lines))line = Integer.parseInt(lines);
                List<Integer> lineList = rr.getResult().stream().filter(Objects::nonNull).map(AllocateOrderDetail::getLineNo)
                        .filter(lineNo -> lineNo != null).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(lineList)) {
                    Integer max = Collections.max(lineList);
                    if (max != null) {
                        line = max;
                    }
                }

            }
            List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
            for (AllocateOrderScItemDetailDTO scItemDetailDTO : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
                AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
                listRequest.setAllocateOrderCode(code);
//                listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
                //008赋值的是scItemCode
                String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetailDTO.getScItemCode());
                if (StringUtils.isBlank(scItemId)){
                    log.error("AllocateOrderWriteRepositoryImpl_passiveSync_queryScItemIdError:{},request:{}",scItemDetailDTO.getScItemCode(),JSON.toJSONString(allocateOrderSyncRequest));
                    response.setCode(scItemDetailDTO.getScItemCode() +"货品查询不存在");
                    return response;
                }
                listRequest.setScItemId(scItemId);
                //22.04.25 电商调拨单使用外部行号镜像匹配
                if (isECommerceOrder){
                    listRequest.setScItemId(null);
                    listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
                }
                //定义一个 原始量
                String oldQuantity = null;
                boolean oldAllocateClosed=false;
                String oldConfirmQuantity = null;
                Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
                //2022.07.21 如果根据外部行号查不到 那就再根据行号查询一下
                if (isECommerceOrder){
                    if (result == null || CollectionUtils.isEmpty(result.getResult()) && StringUtils.isNotBlank(scItemDetailDTO.getLineNo())){
                        listRequest.setScItemId(null);
                        listRequest.setOutAllocateOrderLineId(null);
                        listRequest.setLineNo(Integer.valueOf(scItemDetailDTO.getLineNo()));
                        result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
                    }
                }
                if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                    //更新货品
                    AllocateOrderDetail orderDetail = result.getResult().get(0);
                    oldQuantity = orderDetail.getQuantity();
                    oldAllocateClosed= orderDetail.getClose() != null && orderDetail.getClose();
                    oldConfirmQuantity = orderDetail.getConfirmQuantity();
                    convert(orderDetail, scItemDetailDTO);
                    orderDetail.setScItemId(scItemId);
                    orderDetail.setProductGroup(allocateOrderSyncRequest.getProductGroup());
//                    orderDetail.setConfirmTime(new Date());
                    handleConfirmTime(orderDetail, scItemDetailDTO);
                    orderDetail.setGmt_modified(new Date());
                    orderDetail.setDiscountAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    if (Objects.equals(scItemDetailDTO.getClosed(), Boolean.TRUE)) {
                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    } else if (Objects.equals(orderDetail.getStatus(), AllocateOrderStatus.CLOSED.getValue())) {
                        orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                    }
                    //再次判断下状态 收货 发货的行状态
                    sapUpdateLineStatus(orderDetail);
                    allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,false,oldAllocateClosed,
                            orderDetail.getCloseCode(), oldQuantity,oldConfirmQuantity));
                } else {
                    AllocateOrderDetail orderDetail = new AllocateOrderDetail();
                    convert(orderDetail, scItemDetailDTO);
                    orderDetail.setScItemId(scItemId);
                    //获取主单的type
                    orderDetail.setType(order.getType());
                    orderDetail.setAllocateOrderCode(code);
                    orderDetail.setAllocateOrderId(order.getId());
                    orderDetail.setLineNo(line + 1);
                    orderDetail.setProductGroup(allocateOrderSyncRequest.getProductGroup());
//                    orderDetail.setConfirmTime(new Date());
                    handleConfirmTime(orderDetail, scItemDetailDTO);
                    orderDetail.setGmt_modified(new Date());
                    orderDetail.setDiscountAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    if (Objects.equals(scItemDetailDTO.getClosed(), Boolean.TRUE)) {
                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    }
                    allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
                    line++;
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,true,false,
                            orderDetail.getCloseCode(),null,null));
                }
                //更新一下主单状态..
                AllocateOrderDetailLoadListRequest endQuery = new AllocateOrderDetailLoadListRequest();
                endQuery.setAllocateOrderId(order.getId());
                endQuery.setLimit(MAX_PAGE_SIZE);
                Result<List<AllocateOrderDetail>> endList = allocateOrderDetailService.loadAllocateOrderDetailList(endQuery);
                sapUpdateOrderStatus(endList, order);

//                String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetailDTO.getScItemCode());
                //被动更新 更新
                // 操作 预报单部分 回复数量 关闭状态 生产日期
            }
            //同步回复更新预报单的主子单信
            syncReplyAllocateApplyOrder(allocateApplyOrder,order.getCode(),syncScItemDetails);
        }
        updateAllocateApplyOrderLineId(order.getCode(), allocateApplyOrder.getId());
        response.setCode(code);

        return response;
    }


    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public AllocateOrderSyncResponse passiveSyncApi(AllocateOrderSyncRequest allocateOrderSyncRequest) {
        //先检验下参数情况

        AllocateOrderSyncResponse response = new AllocateOrderSyncResponse();
        if (allocateOrderSyncRequest == null) {
            response.setCode("请求参数不能为空");
            return response;
        }
        if (CollectionUtils.isEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            response.setCode("物料不能为空");
            return response;
        }
        List<String> collect = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode())).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            response.setCode("物料不能为空");
            return response;
        }
//        if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > collect.size()) {
//            response.setCode("物料不能重复");
//            return response;
//        }
        Set<String> outAllocateOrderLineIdSet = allocateOrderSyncRequest.getAllocateOrderScItemDetails()
                .stream().map(AllocateOrderScItemDetailDTO::getThirdLineNo).collect(Collectors.toSet());
        if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > outAllocateOrderLineIdSet.size()){
            response.setCode("外部调拨单行号不能重复");
            return response;
        }

        boolean isECommerceOrder = InfoUtil.isECommerceOrder(null);
//        if (isECommerceOrder){
////            Set<String> outAllocateOrderLineIdSet = allocateOrderSyncRequest.getAllocateOrderScItemDetails()
////                    .stream().map(AllocateOrderScItemDetailDTO::getOutAllocateOrderLineId).collect(Collectors.toSet());
////            if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > outAllocateOrderLineIdSet.size()){
////                response.setCode("外部调拨单行号不能重复");
////                return response;
////            }
//        }else {
////            if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > collect.size()) {
////                response.setCode("物料不能重复");
////                return response;
////            }
//        }

        //找出预报单
//        AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
//        if (!StringUtils.isAllBlank(allocateOrderSyncRequest.getAllocateApplyOrderCode(),  allocateOrderSyncRequest.getOutAllocateApplyOrderId())) {
//            AllocateApplyOrderLoadListRequest applyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
//            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getAllocateApplyOrderCode())){
//                applyOrderLoadListRequest.setCode(allocateOrderSyncRequest.getAllocateApplyOrderCode());
//            }
//            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getOutAllocateApplyOrderId())){
//                applyOrderLoadListRequest.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
//            }
//            Result<List<AllocateApplyOrder>> applyResult = allocateApplyOrderService.loadAllocateApplyOrderList(applyOrderLoadListRequest);
//            if (applyResult != null && CollectionUtils.isNotEmpty(applyResult.getResult())) {
//                allocateApplyOrder = applyResult.getResult().get(0);
//                if (AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrder.getStatus())) {
//                    response.setCode("预报单是待推送状态,不允许同步");
//                    return response;
//                }
//            }
//        }
//        AllocateOrderLoadListRequest queryRequest = new AllocateOrderLoadListRequest();
//        queryRequest.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
//        queryRequest.setCode(allocateOrderSyncRequest.getCode());
//        Result<List<AllocateOrder>> queryResult = allocateOrderService.loadAllocateOrderList(queryRequest);
//        if (queryResult != null && CollectionUtils.isNotEmpty(queryResult.getResult())) {
//            allocateOrderSyncRequest.setCode(queryResult.getResult().get(0).getCode());
//        }

        String code = allocateOrderSyncRequest.getCode();
        String thirdAllocateOrderCode = allocateOrderSyncRequest.getThirdAllocateOrderId();
        if (StringUtils.isBlank(code)) {
//            AllocateOrderLoadListRequest orderLoadListRequest = new AllocateOrderLoadListRequest();
//            orderLoadListRequest.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
//            Result<List<AllocateOrder>> orderListResult = allocateOrderService.loadAllocateOrderList(orderLoadListRequest);
//            if (orderListResult != null && CollectionUtils.isNotEmpty(orderListResult.getResult())) {
//                response.setCode("该外部单号已经存在,不允许新增");
//                return response;
//            }
            code = CodeUtil.planCode();
            //新增调拨单
            AllocateOrder allocateOrder = JsonUtil.convert(allocateOrderSyncRequest, AllocateOrder.class);
            //代表是常温产品
            allocateOrder.setProductGroup(allocateOrderSyncRequest.getProductGroup() == null ? "11" : allocateOrderSyncRequest.getProductGroup());
            allocateOrder.setCode(code);
            allocateOrder.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
//            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
//            allocateOrder.setAllocateApplyOrderCode(StringUtils.isBlank(allocateApplyOrder.getCode()) ? null : allocateApplyOrder.getCode());
//            if (allocateApplyOrder.getType() != null) {
//                allocateOrder.setType(allocateApplyOrder.getType());
//            }
            allocateOrder.setType(allocateOrderSyncRequest.getType());
            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司 代码在下面
//            allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
            //如果收货仓不是空的.
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getReceiveAreaId())) {
                allocateOrder.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
            }
//            else {
//                allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId() == null ? null :
//                        allocateApplyOrder.getReceiveWarehouseId() + "");
//            }
//            allocateOrder.setIsDTC(allocateApplyOrder.getIsDTC() != null && allocateApplyOrder.getIsDTC());
//            allocateOrder.setSapSalesOrgId(allocateApplyOrder.getHeadquartersOrganizationCode());
            //如果出入库仓改变的话, 更新一下.
            Map<String, WmsSDO> wmsMap = InfoUtil.getWmsSDOMapByAreaList(Lists.newArrayList(allocateOrder.getShipAreaId(), allocateOrder.getReceiveAreaId()));
            WmsSDO shipWmsSDO = wmsMap.get(allocateOrder.getShipAreaId());
            WmsSDO receiveWmsSDO = wmsMap.get(allocateOrder.getReceiveAreaId());

            allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
            allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());

            //features 收发货仓的工厂编码和库存地点
            Map<String,String> featuresMap = Maps.newHashMap();
            featuresMap.put(FeaturesKey.DELIVERY_FACTORY_CODE,shipWmsSDO.getFactoryCode());
            featuresMap.put(FeaturesKey.DELIVERY_STORAGE_LOCATION_CODE,shipWmsSDO.getInventoryCode());
            featuresMap.put(FeaturesKey.RECEIVE_FACTORY_CODE,receiveWmsSDO.getFactoryCode());
            featuresMap.put(FeaturesKey.RECEIVE_STORAGE_LOCATION_CODE,receiveWmsSDO.getInventoryCode());

            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
            allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
//            allocateOrder.setShipWarehouseId(allocateOrderSyncRequest.getShipWarehouseId());
//            allocateOrder.setShipOrgId(allocateOrderSyncRequest.getSapSalesOrgId());
//            allocateOrder.setReceiveWarehouseId(allocateOrderSyncRequest.getReceiveWarehouseId());
//            allocateOrder.setReceiveOrgId(allocateOrderSyncRequest.getSapSalesOrgId());
//            if (allocateApplyOrder.getApplyOrgId() == null && StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
////                GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
////                getOrganiztionByIdRequest.setId(allocateOrder.getReceiveOrgId());
////                OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
////                if(organiztionById != null){
////                    allocateOrder.setApplyOrgId(organiztionById.getParentId());
////                }
//                OrganizationSDO orgSDO = getOrgSDO(allocateOrder.getReceiveOrgId());
//                if (orgSDO != null){
//                    allocateOrder.setApplyOrgId(orgSDO.getParentId());
//                }
//            }
            allocateOrder.setConfirmTime(new Date());
            if (allocateOrderSyncRequest.getDocDate() == null) {
                allocateOrder.setDocDate(InfoUtil.docDate());
            } else {
                allocateOrder.setDocDate(allocateOrderSyncRequest.getDocDate());
            }
//            //如果是全关闭 那就标记为关闭
//            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
//                boolean allClosed = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
//                        .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
//                if (allClosed) {
//                    allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                } else {
//                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                }
//            }

            Integer statusValue = AllocateOrderStatus.DRAFT.getValue();
            // submitFlag:true提交（待推送），false不提交（草稿）
            if(allocateOrderSyncRequest.getSubmitFlag()){
                statusValue = AllocateOrderStatus.WAIT_PUSH.getValue();
            }
            allocateOrder.setStatus(statusValue);
            //成本中心 客户采购参考号 -- 008 更新时 客户成本中心不传递 客户采购参考号
//            allocateOrder.setSapCostCenter(allocateApplyOrder.getSapCostCenter());
//            allocateOrder.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
//            allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
            allocateOrder.setExpectedDeliveryDate(allocateOrderSyncRequest.getExpectedDeliveryDate());
            allocateOrder.setRequestId(allocateOrderSyncRequest.getRequestId());
            allocateOrder.setThirdAllocateOrderId(allocateOrderSyncRequest.getThirdAllocateOrderId());
            allocateOrder.setRemark(allocateOrderSyncRequest.getRemark());
            allocateOrder.setFeatures(allocateOrderSyncRequest.getFeatures());


            allocateOrder.setAllocateApplyOrderId(allocateOrderSyncRequest.getAllocateApplyOrderId());
            allocateOrder.setRelatedAllocateOrderCode(allocateOrderSyncRequest.getRelatedAllocateOrderCode());
            allocateOrder.setFulfillmentTypeCode(allocateOrderSyncRequest.getFulfillmentTypeCode());
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getOrderTag())) {
                allocateOrder.setOrderTag(StringUtils.join(allocateOrderSyncRequest.getOrderTag().toArray(),","));
            }
            allocateOrder.setAutoFulfillment(allocateOrderSyncRequest.getAutoFulfillment());
            allocateOrder.setCreatorName(allocateOrderSyncRequest.getCreator());
            allocateOrder.setModifierName(allocateOrderSyncRequest.getCreator());
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getTakeEffectDate())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = sdf.parse(allocateOrderSyncRequest.getTakeEffectDate());
                    allocateOrder.setBeginDate(parse);
                } catch (ParseException e) {
                    response.setCode("生效日期格式不正确");
                    return response;
                }
            }
            allocateOrder.setShipMethod(allocateOrderSyncRequest.getShipMethod());
            allocateOrder.setThirdAllocateOrderId(allocateOrderSyncRequest.getThirdAllocateOrderId());
            allocateOrder.setRelatedAllocateOrderCode(allocateOrderSyncRequest.getRelatedAllocateOrderCode());
            allocateOrder.setPriority(allocateOrderSyncRequest.getPriority());
            allocateOrder.setTransferWarehouseId(allocateOrderSyncRequest.getTransferWarehouseId());
            if (MapUtils.isNotEmpty(featuresMap)){
                allocateOrder.setBizFeatures(FeatureUtil.toString(featuresMap));
            }
            CreateAllocateOrderResponse createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);

            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                int i = 1;
                //用来更新
                List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
                for (AllocateOrderScItemDetailDTO scItemDetail : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
                    AllocateOrderDetail detail = JsonUtil.convert(scItemDetail, AllocateOrderDetail.class);
                    detail.setAllocateOrderCode(code);
                    detail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(scItemDetail.getProductDate()));
                    detail.setAllocateOrderId(createAllocateOrderResponse.getLastInsertId());
                    detail.setType(allocateOrderSyncRequest.getType());
                    detail.setAllocateApplyOrderLineId(scItemDetail.getAllocateApplyOrderLineId());
                    //商品转换 需要把sap的转换成我们的

                    String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetail.getScItemCode());

                    //如果货品查询失败返回
                    if (StringUtils.isBlank(scItemId)){
                        log.error("AllocateOrderWriteRepositoryImpl_passiveSync_queryScItemIdError:{},request:{}",scItemDetail.getScItemCode(),JSON.toJSONString(allocateOrderSyncRequest));
                        response.setCode(scItemDetail.getScItemCode() +"货品查询不存在");
                        return response;
                    }
//                    detail.setScItemId(InfoUtil.deleteZeroPrefix(scItemDetail.getScItemCode()));
                    detail.setScItemId(scItemId);
                    detail.setScItemName(scItemDetail.getTitle());
//                    detail.setScItemCode(InfoUtil.deleteZeroPrefix(scItemDetail.getScItemCode()));
                    detail.setScItemCode(InfoUtil.subStringScItmCode(scItemDetail.getScItemCode()));
                    detail.setClose(scItemDetail.getClosed());
//                    detail.setStatus(Objects.equals(scItemDetail.getClosed(), Boolean.TRUE) ?
//                            AllocateOrderStatus.CLOSED.getValue() : AllocateOrderStatus.Shipment_Processing.getValue());
                    detail.setStatus(statusValue);
                    detail.setProductGroup(allocateOrderSyncRequest.getProductGroup() == null ? SC_ITEM_PRODUCT_GROUP_CODE : allocateOrderSyncRequest.getProductGroup());

                    detail.setReturnOrder(allocateOrder.getReturnOrder());
                    detail.setLineNo(i);
                    detail.setQuantity(InfoUtil.trim(detail.getQuantity()));
                    detail.setPrice(InfoUtil.trim(detail.getPrice()));
                    handleConfirmTime(detail, scItemDetail);
                    detail.setConfirmQuantity(InfoUtil.trim(scItemDetail.getConfirmQuantity()));
                    detail.setDiscountAmount(InfoUtil.trim(scItemDetail.getSubTotalAmount()));
                    detail.setSubTotalAmount(InfoUtil.trim(scItemDetail.getSubTotalAmount()));
                    detail.setOutAllocateOrderLineId(scItemDetail.getOutAllocateOrderLineId());
                    detail.setRemarks(scItemDetail.getRemark());
                    detail.setRelatedAllocateSubOrderId(scItemDetail.getRelatedAllocateSubOrderId());
                    detail.setThirdLineNo(scItemDetail.getThirdLineNo());
                    detail.setAllocateApplyOrderLineId(scItemDetail.getAllocateApplyOrderLineId());
                    detail.setCreatorName(allocateOrderSyncRequest.getCreator());
                    detail.setModifierName(allocateOrderSyncRequest.getCreator());
                    allocateOrderDetailService.createAllocateOrderDetail(detail);

                    i++;
                    // 操作 预报单部分 回复数量 关闭状态 生产日期
                    //组装同步更新预报单的明细数据
                    syncScItemDetails.add(convert2SyncScItemDetail(detail,true,false,
                            scItemDetail.getCloseCode(), null,null));
                }
                //更改预报单主子单状态,回复数量 拒接原因...
//                syncReplyAllocateApplyOrder(allocateApplyOrder,allocateOrder.getCode(),syncScItemDetails);
            }
//            delivery(allocateOrderSyncRequest.getOutAllocateOrderId());
            response.setCode(code);
            response.setThirdAllocateOrderId(thirdAllocateOrderCode);
            return response;
        }
        //下面是更新操作的操作
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setCode(allocateOrderSyncRequest.getCode());
        Result<List<AllocateOrder>> orderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (orderList == null || CollectionUtils.isEmpty(orderList.getResult())) {
            response.setCode("未查询到该调拨单号");
            return response;
        }

        AllocateOrder order = orderList.getResult().get(0);
        //如果

//        if (!Objects.equals(order.getOutAllocateOrderId(),allocateOrderSyncRequest.getOutAllocateOrderId())){
//            response.setCode("调拨单号和外部调拨单号关系不匹配");
//            return response;
//        }
        //如果是008传递过来是待推送,我们就直接先改成待发货状态
        if (Objects.equals(order.getStatus(), AllocateOrderStatus.WAIT_PUSH.getValue())) {
            order.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getOutAllocateOrderId())){
                order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
            }
            allocateOrderService.updateAllocateOrder(order);
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderId(order.getId());
            allocateOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
                for (AllocateOrderDetail detail : result.getResult()) {
                    //如果是待推送状态,就修改子单明细的状态
                    if (AllocateOrderStatus.WAIT_PUSH.getValue().equals(detail.getStatus())){
                        detail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        allocateOrderDetailService.updateAllocateOrderDetail(detail);
                    }
                }
            }
//            response.setCode("调拨单未推送成功或回调失败,不允许更新");
//            return response;
        }


        AllocateOrderDetailLoadListRequest checkRequest = new AllocateOrderDetailLoadListRequest();
        checkRequest.setAllocateOrderId(order.getId());
        checkRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> checkResult = allocateOrderDetailService.loadAllocateOrderDetailList(checkRequest);
        if (checkResult != null && CollectionUtils.isNotEmpty(checkResult.getResult()) && !isECommerceOrder) {
            //找出现有的明细; 如果传递的商品有新增的.
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                List<String> scItemCodes = checkResult.getResult().stream()
                        .filter(y -> StringUtils.isNotBlank(y.getScItemCode()))
                        .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode()))
                        .distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(scItemCodes)) {
                    List<String> list = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                            .map(z -> InfoUtil.subStringScItmCode(z.getScItemCode())).collect(Collectors.toList());
                    boolean b = scItemCodes.stream().anyMatch(x -> !list.contains(x));
                    if (b) {
                        response.setCode("物料编码不允许修改");
                        return response;
                    }
                }
            }
        }


        order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
        order.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
        order.setTypeCard(allocateOrderSyncRequest.getTypeCard());
        order.setSapChannel(allocateOrderSyncRequest.getSapChannel());
        order.setProductGroup(allocateOrderSyncRequest.getProductGroup());
        order.setShipAreaId(allocateOrderSyncRequest.getShipAreaId());
        order.setShipWarehouseId(allocateOrderSyncRequest.getShipWarehouseId());
        //如果有收货仓改变
        if (StringUtils.isNotBlank(allocateOrderSyncRequest.getReceiveAreaId())) {
            order.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
        }
        order.setReceiveWarehouseId(allocateOrderSyncRequest.getReceiveWarehouseId());
        order.setCreateTime(allocateOrderSyncRequest.getCreateTime());
        order.setShipMethod(allocateOrderSyncRequest.getShipMethod());
        order.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
        order.setFeatures(allocateOrderSyncRequest.getFeatures());
        order.setRemark(allocateOrderSyncRequest.getRemark());
        //如果出入库仓改变的话, 更新一下.
        WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(order.getShipAreaId());
        order.setShipWarehouseId(shipWmsSDO.getWarehouseId());
        order.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(order.getReceiveAreaId());
        order.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
        order.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
        if (allocateOrderSyncRequest.getDocDate() == null) {
            order.setDocDate(InfoUtil.docDate());
        } else {
            order.setDocDate(allocateOrderSyncRequest.getDocDate());
        }
        order.setGmt_modified(new Date());
        //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
//        if (allocateApplyOrder.getApplyOrgId() == null && StringUtils.isNotBlank(order.getReceiveOrgId())){
////            GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
////            getOrganiztionByIdRequest.setId(order.getReceiveOrgId());
////            OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
////            if(organiztionById != null){
////                order.setApplyOrgId(organiztionById.getParentId());
////            }
//            OrganizationSDO orgSDO = getOrgSDO(order.getReceiveOrgId());
//            if (orgSDO != null){
//                order.setApplyOrgId(orgSDO.getParentId());
//            }
//        }
//        order.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
        if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            boolean allClosed = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                    .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
            if (allClosed) {
                order.setStatus(AllocateOrderStatus.CLOSED.getValue());
            } else {
                if (order.getStatus() == null) {
                    order.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                }
            }
        }
        // 参考号 和成本中心
//        order.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
//        order.setSapCostCenter(allocateApplyOrder.getSapCostCenter());
//        order.setExpectedDeliveryDate(allocateOrderSyncRequest.getExpectedDeliveryDate());
//        if (StringUtils.isBlank(order.getAllocateApplyOrderId()) && allocateApplyOrder.getId() != null){
//            order.setAllocateApplyOrderId(allocateApplyOrder.getId().toString());
//        }
//        if (StringUtils.isBlank(order.getAllocateApplyOrderCode()) && StringUtils.isNotBlank(allocateApplyOrder.getCode())){
//            order.setAllocateApplyOrderCode(allocateApplyOrder.getCode());
//        }
        allocateOrderService.updateAllocateOrder(order);

        if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            //获取最大的行号
            AllocateOrderDetailLoadListRequest request = new AllocateOrderDetailLoadListRequest();
            request.setAllocateOrderCode(code);
            request.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> rr = allocateOrderDetailService.loadAllocateOrderDetailList(request);
            int line = 1;
            if (rr != null && CollectionUtils.isNotEmpty(rr.getResult())) {
//                String lines = rr.getResult().stream().filter(Objects::nonNull).filter(orderDetail -> StringUtils.isNotBlank(orderDetail.getLineNo()))
//                        .max(Comparator.comparing(AllocateOrderDetail::getLineNo)).get().getLineNo();
//                if (StringUtils.isNotBlank(lines))line = Integer.parseInt(lines);
                List<Integer> lineList = rr.getResult().stream().filter(Objects::nonNull).map(AllocateOrderDetail::getLineNo)
                        .filter(lineNo -> lineNo != null).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(lineList)) {
                    Integer max = Collections.max(lineList);
                    if (max != null) {
                        line = max;
                    }
                }

            }
            List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
            for (AllocateOrderScItemDetailDTO scItemDetailDTO : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
                AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
                listRequest.setAllocateOrderCode(code);
//                listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
                //008赋值的是scItemCode
                String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetailDTO.getScItemCode());
                if (StringUtils.isBlank(scItemId)){
                    log.error("AllocateOrderWriteRepositoryImpl_passiveSync_queryScItemIdError:{},request:{}",scItemDetailDTO.getScItemCode(),JSON.toJSONString(allocateOrderSyncRequest));
                    response.setCode(scItemDetailDTO.getScItemCode() +"货品查询不存在");
                    return response;
                }
                listRequest.setScItemId(scItemId);
                //22.04.25 电商调拨单使用外部行号镜像匹配
                if (isECommerceOrder){
                    listRequest.setScItemId(null);
                    listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
                }
                //定义一个 原始量
                String oldQuantity = null;
                boolean oldAllocateClosed=false;
                String oldConfirmQuantity = null;
                Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
                //2022.07.21 如果根据外部行号查不到 那就再根据行号查询一下
                if (isECommerceOrder){
                    if (result == null || CollectionUtils.isEmpty(result.getResult()) && StringUtils.isNotBlank(scItemDetailDTO.getLineNo())){
                        listRequest.setScItemId(null);
                        listRequest.setOutAllocateOrderLineId(null);
                        listRequest.setLineNo(Integer.valueOf(scItemDetailDTO.getLineNo()));
                        result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
                    }
                }
                if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                    //更新货品
                    AllocateOrderDetail orderDetail = result.getResult().get(0);
                    oldQuantity = orderDetail.getQuantity();
                    oldAllocateClosed= orderDetail.getClose() != null && orderDetail.getClose();
                    oldConfirmQuantity = orderDetail.getConfirmQuantity();
                    convert(orderDetail, scItemDetailDTO);
                    orderDetail.setScItemId(scItemId);
                    orderDetail.setProductGroup(allocateOrderSyncRequest.getProductGroup());
//                    orderDetail.setConfirmTime(new Date());
                    handleConfirmTime(orderDetail, scItemDetailDTO);
                    orderDetail.setGmt_modified(new Date());
                    orderDetail.setDiscountAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    if (Objects.equals(scItemDetailDTO.getClosed(), Boolean.TRUE)) {
                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    } else if (Objects.equals(orderDetail.getStatus(), AllocateOrderStatus.CLOSED.getValue())) {
                        orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                    }
                    //再次判断下状态 收货 发货的行状态
                    sapUpdateLineStatus(orderDetail);
                    allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,false,oldAllocateClosed,
                            orderDetail.getCloseCode(), oldQuantity,oldConfirmQuantity));
                } else {
                    AllocateOrderDetail orderDetail = new AllocateOrderDetail();
                    convert(orderDetail, scItemDetailDTO);
                    orderDetail.setScItemId(scItemId);
                    //获取主单的type
                    orderDetail.setType(order.getType());
                    orderDetail.setAllocateOrderCode(code);
                    orderDetail.setAllocateOrderId(order.getId());
                    orderDetail.setLineNo(line + 1);
                    orderDetail.setProductGroup(allocateOrderSyncRequest.getProductGroup());
//                    orderDetail.setConfirmTime(new Date());
                    handleConfirmTime(orderDetail, scItemDetailDTO);
                    orderDetail.setGmt_modified(new Date());
                    orderDetail.setDiscountAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    if (Objects.equals(scItemDetailDTO.getClosed(), Boolean.TRUE)) {
                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    }
                    allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
                    line++;
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,true,false,
                            orderDetail.getCloseCode(),null,null));
                }
                //更新一下主单状态..
                AllocateOrderDetailLoadListRequest endQuery = new AllocateOrderDetailLoadListRequest();
                endQuery.setAllocateOrderId(order.getId());
                endQuery.setLimit(MAX_PAGE_SIZE);
                Result<List<AllocateOrderDetail>> endList = allocateOrderDetailService.loadAllocateOrderDetailList(endQuery);
                sapUpdateOrderStatus(endList, order);

//                String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetailDTO.getScItemCode());
                //被动更新 更新
                // 操作 预报单部分 回复数量 关闭状态 生产日期
            }
            //同步回复更新预报单的主子单信
//            syncReplyAllocateApplyOrder(allocateApplyOrder,order.getCode(),syncScItemDetails);
        }
//        updateAllocateApplyOrderLineId(order.getCode(), allocateApplyOrder.getId());
        response.setCode(code);

        return response;
    }
    public static void convert(AllocateOrderDetail orderDetail, AllocateOrderScItemDetailDTO dto) {
        orderDetail.setOutAllocateOrderLineId(dto.getOutAllocateOrderLineId());
        orderDetail.setScItemCode(dto.getScItemCode());
        orderDetail.setScItemId(dto.getScItemCode());
        orderDetail.setQuantity(InfoUtil.trim(dto.getQuantity()));
        orderDetail.setApplyQuantity(StringUtils.isBlank(dto.getApplyQuantity()) ? null :
                Long.parseLong(dto.getApplyQuantity()));
//        orderDetail.setType(AllocateOrderTypeEnum.PLAN.getType());
        //008 013 接口只有在它
        if (orderDetail.getStatus() == null) {
            orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
        }
        orderDetail.setUnit(dto.getUnit());
        orderDetail.setPrice(InfoUtil.trim(dto.getPrice()));
        orderDetail.setTaxRate(InfoUtil.trim(dto.getTaxRate()));
        orderDetail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
        orderDetail.setExpectedProduceDate(dto.getExpectedProduceDate());
        orderDetail.setClose(dto.getClosed());
        orderDetail.setCloseReason(dto.getClosedReason());
        orderDetail.setFeatures(dto.getFeatures());
        orderDetail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
        orderDetail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
        orderDetail.setConfirmQuantity(InfoUtil.trim(dto.getConfirmQuantity()));
        orderDetail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
    }
//    public AllocateOrderSyncResponse passiveSync(AllocateOrderSyncRequest allocateOrderSyncRequest) {
//        AllocateOrderSyncResponse responseResponse = new AllocateOrderSyncResponse();
//
//        AllocateOrder allocateOrder = new AllocateOrder();
//        allocateOrder.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
//        allocateOrder.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
//        allocateOrder.setAllocateApplyOrderCode(allocateOrderSyncRequest.getAllocateApplyOrderCode());
//        allocateOrder.setTypeCard(allocateOrderSyncRequest.getTypeCard());
//        allocateOrder.setSapChannel(allocateOrderSyncRequest.getSapChannel());
//        allocateOrder.setShipAreaId(allocateOrderSyncRequest.getShipAreaId());
//        allocateOrder.setShipWarehouseId(allocateOrderSyncRequest.getShipWarehouseId());
//        allocateOrder.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
////        allocateOrder.setGmtCreate(allocateOrderSyncRequest.getGmtCreate());
////        allocateOrder.setGmtModified(allocateOrderSyncRequest.getGmtModified());
//        allocateOrder.setShipMethod(allocateOrderSyncRequest.getShipMethod());
//        allocateOrder.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
//        allocateOrder.setFeatures(allocateOrderSyncRequest.getFeatures());
//        allocateOrder.setApplyOrgId(allocateOrderSyncRequest.getApplyOrgId());
//        allocateOrder.setType(allocateOrderSyncRequest.getType());
//        allocateOrder.setStatus(allocateOrderSyncRequest.getStatus());
//        allocateOrder.setDocDate(allocateOrderSyncRequest.getDocDate());
////        allocateOrder.setExpectedDeliveryDate(allocateOrderSyncRequest.getExpectedDeliveryDate());
//        allocateOrder.setCreateTime(allocateOrderSyncRequest.getCreateTime());
//        AllocateApplyOrderLoadListRequest applyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
//        applyOrderLoadListRequest.setCode(allocateOrderSyncRequest.getAllocateApplyOrderCode());
//        Result<List<AllocateApplyOrder>> applyResult = allocateApplyOrderService.loadAllocateApplyOrderList(applyOrderLoadListRequest);
//        AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
//        //获取到调拨预报单
//        if (applyResult !=null && CollectionUtils.isNotEmpty(applyResult.getResult())){
//            allocateApplyOrder = applyResult.getResult().get(0);
//        }
//        allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
//        allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null?null:allocateApplyOrder.getId()+"");
//        allocateOrder.setRemark(allocateOrder.getRemark());
//        allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null?null:allocateApplyOrder.getApplyOrgId()+"");
//
//        //查询下调拨预报单
//        //如果是空
//        CreateAllocateOrderResponse createAllocateOrderResponse;
//        UpdateAllocateOrderResponse updateAllocateOrderResponse;
//        if (StringUtils.isBlank(allocateOrderSyncRequest.getCode())){
//            String code = "STO" +UUID.randomUUID().toString().replace("-","").substring(0,10);
//            allocateOrder.setCode(code);
//            createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);
//            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())){
//                int line = 1;
//                for (AllocateOrderScItemDetailDTO scItemDetailDTO : allocateOrderSyncRequest.getAllocateOrderScItemDetails()){
//                    AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
//                    allocateOrderDetail.setLineNo(line+"");
//                    allocateOrderDetail.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
//                    allocateOrderDetail.setScItemCode(scItemDetailDTO.getScItemCode());
//                    allocateOrderDetail.setScItemId(scItemDetailDTO.getScItemCode());
//                    allocateOrderDetail.setQuantity(scItemDetailDTO.getQuantity());
//                    allocateOrderDetail.setApplyQuantity(StringUtils.isBlank(scItemDetailDTO.getApplyQuantity())?null:
//                            Long.parseLong(scItemDetailDTO.getApplyQuantity()));
//                    allocateOrderDetail.setType(allocateOrderSyncRequest.getType());
//                    allocateOrderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                    allocateOrderDetail.setAllocateOrderId(createAllocateOrderResponse.getLastInsertId());
//                    allocateOrderDetail.setAllocateOrderCode(code);
//                    allocateOrderDetail.setUnit(scItemDetailDTO.getUnit());
//                    allocateOrderDetail.setPrice(getPrice(scItemDetailDTO.getPrice()));
//                    allocateOrderDetail.setTaxRate(scItemDetailDTO.getTaxRate());
//                    allocateOrderDetail.setSubTotalAmount(scItemDetailDTO.getSubTotalAmount());
//                    allocateOrderDetail.setExpectedProduceDate(scItemDetailDTO.getExpectedProduceDate());
//                    allocateOrderDetail.setClose(scItemDetailDTO.getClosed());
//                    allocateOrderDetail.setFeatures(scItemDetailDTO.getFeatures());
//                    allocateOrderDetail.setExpectedDeliveryDate(scItemDetailDTO.getExpectedDeliveryDate());
//                    allocateOrderDetail.setOutAllocateApplyOrderLineId(scItemDetailDTO.getOutAllocateApplyOrderLineId());
////                    allocateOrderDetail.setPrice;
//                    allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
//                }
//            }
//            responseResponse.setCode(code);
//            return responseResponse;
//        }else {
//            //查询下
//            AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
//            allocateOrderLoadListRequest.setCode(allocateOrderSyncRequest.getCode());
//            Result<List<AllocateOrder>> loadAllocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
//            if (loadAllocateOrderList == null || CollectionUtils.isEmpty(loadAllocateOrderList.getResult())){
//                AllocateOrderSyncResponse allocateOrderSyncResponse = new AllocateOrderSyncResponse();
//                return allocateOrderSyncResponse;
//            }
//            AllocateOrder order = loadAllocateOrderList.getResult().get(0);
//            order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
//            order.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
//            order.setAllocateApplyOrderCode(allocateOrderSyncRequest.getAllocateApplyOrderCode());
//            order.setTypeCard(allocateOrderSyncRequest.getTypeCard());
//            order.setSapChannel(allocateOrderSyncRequest.getSapChannel());
//            order.setShipAreaId(allocateOrderSyncRequest.getShipAreaId());
//            order.setShipWarehouseId(allocateOrderSyncRequest.getShipWarehouseId());
//            order.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
//            order.setShipMethod(allocateOrderSyncRequest.getShipMethod());
//            order.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
//            order.setFeatures(allocateOrderSyncRequest.getFeatures());
//            order.setApplyOrgId(allocateOrderSyncRequest.getApplyOrgId());
//            order.setType(allocateOrderSyncRequest.getType());
//            order.setStatus(allocateOrderSyncRequest.getStatus());
//            order.setDocDate(allocateOrderSyncRequest.getDocDate());
//            if (allocateApplyOrder.getHopeDeliveryTime() == null){
//                order.setExpectedDeliveryDate(allocateOrderSyncRequest.getExpectedDeliveryDate());
//            }else {
//                order.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
//            }
//            //如果是更新操作.
//            allocateOrderService.updateAllocateOrder(order);
//            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())){
//                AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
//                listRequest.setAllocateOrderCode(order.getCode());
////                listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
////                listRequest.setScItemCode(scItemDetailDTO.getScItemCode());
//                Result<List<AllocateOrderDetail>> orderResult = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
//                List<AllocateOrderDetail> orderDetails = Lists.newArrayList();
//                if (orderResult != null && CollectionUtils.isNotEmpty(orderResult.getResult())){
//                    orderDetails = orderResult.getResult();
//                }
//                int line = 1;
//                if (CollectionUtils.isNotEmpty(orderDetails)){
//                    String lineStr = orderDetails.stream().filter(Objects::nonNull)
//                            .filter(x->StringUtils.isNotBlank(x.getLineNo())).max(Comparator.comparing(AllocateOrderDetail::getLineNo)).get().getLineNo();
//                    line = Integer.parseInt(lineStr) + 1;
//                    for (AllocateOrderScItemDetailDTO scItemDetailDTO : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
//                        AllocateOrderDetail target = orderDetails.stream().filter(y->Objects.equals(scItemDetailDTO.getCode(),y.getAllocateOrderCode())
//                                && Objects.equals(scItemDetailDTO.getScItemCode(),y.getScItemCode()))
//                                .findFirst().get();
//                        if (target == null){
//                            AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
//                            allocateOrderDetail.setLineNo(line+"");
//                            allocateOrderDetail.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
//                            allocateOrderDetail.setScItemCode(scItemDetailDTO.getScItemCode());
//                            allocateOrderDetail.setScItemId(scItemDetailDTO.getScItemCode());
//                            allocateOrderDetail.setQuantity(scItemDetailDTO.getQuantity());
//                            allocateOrderDetail.setApplyQuantity(StringUtils.isBlank(scItemDetailDTO.getApplyQuantity())?null:
//                                    Long.parseLong(scItemDetailDTO.getApplyQuantity()));
//                            allocateOrderDetail.setType(allocateOrderSyncRequest.getType());
//                            allocateOrderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                            allocateOrderDetail.setAllocateOrderId(order.getId() +"");
//                            allocateOrderDetail.setAllocateOrderCode(order.getCode());
//                            allocateOrderDetail.setUnit(scItemDetailDTO.getUnit());
//                            allocateOrderDetail.setPrice(getPrice(scItemDetailDTO.getPrice()));
//                            allocateOrderDetail.setTaxRate(scItemDetailDTO.getTaxRate());
//                            allocateOrderDetail.setSubTotalAmount(scItemDetailDTO.getSubTotalAmount());
//                            allocateOrderDetail.setExpectedProduceDate(scItemDetailDTO.getExpectedProduceDate());
//                            allocateOrderDetail.setClose(scItemDetailDTO.getClosed());
//                            allocateOrderDetail.setFeatures(scItemDetailDTO.getFeatures());
//                            allocateOrderDetail.setExpectedDeliveryDate(scItemDetailDTO.getExpectedDeliveryDate());
//                            allocateOrderDetail.setOutAllocateApplyOrderLineId(scItemDetailDTO.getOutAllocateApplyOrderLineId());
//                            allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
//                        }else {
//                            target.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
//                            target.setScItemCode(scItemDetailDTO.getScItemCode());
//                            target.setScItemId(scItemDetailDTO.getScItemCode());
//                            target.setQuantity(scItemDetailDTO.getQuantity());
//                            target.setApplyQuantity(StringUtils.isBlank(scItemDetailDTO.getApplyQuantity())?null:
//                                    Long.parseLong(scItemDetailDTO.getApplyQuantity()));
//                            target.setType(allocateOrderSyncRequest.getType());
//                            target.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                            target.setAllocateOrderId(order.getId() +"");
//                            target.setAllocateOrderCode(order.getCode());
//                            target.setUnit(scItemDetailDTO.getUnit());
//                            target.setPrice(getPrice(scItemDetailDTO.getPrice()));
//                            target.setTaxRate(scItemDetailDTO.getTaxRate());
//                            target.setSubTotalAmount(scItemDetailDTO.getSubTotalAmount());
//                            target.setExpectedProduceDate(scItemDetailDTO.getExpectedProduceDate());
//                            target.setClose(scItemDetailDTO.getClosed());
//                            target.setFeatures(scItemDetailDTO.getFeatures());
//                            target.setExpectedDeliveryDate(scItemDetailDTO.getExpectedDeliveryDate());
//                            target.setOutAllocateApplyOrderLineId(scItemDetailDTO.getOutAllocateApplyOrderLineId());
//                            allocateOrderDetailService.updateAllocateOrderDetail(target);
//                        }
//                    }
//
//                    line ++;
//                }else {
//                    for (AllocateOrderScItemDetailDTO scItemDetailDTO : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
//                        AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
//                        allocateOrderDetail.setLineNo(line+"");
//                        allocateOrderDetail.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
//                        allocateOrderDetail.setScItemCode(scItemDetailDTO.getScItemCode());
//                        allocateOrderDetail.setScItemId(scItemDetailDTO.getScItemCode());
//                        allocateOrderDetail.setQuantity(scItemDetailDTO.getQuantity());
//                        allocateOrderDetail.setApplyQuantity(StringUtils.isBlank(scItemDetailDTO.getApplyQuantity())?null:
//                                Long.parseLong(scItemDetailDTO.getApplyQuantity()));
//                        allocateOrderDetail.setType(allocateOrderSyncRequest.getType());
//                        allocateOrderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                        allocateOrderDetail.setAllocateOrderId(order.getId() +"");
//                        allocateOrderDetail.setAllocateOrderCode(order.getCode());
//                        allocateOrderDetail.setUnit(scItemDetailDTO.getUnit());
//                        allocateOrderDetail.setPrice(getPrice(scItemDetailDTO.getPrice()));
//                        allocateOrderDetail.setTaxRate(scItemDetailDTO.getTaxRate());
//                        allocateOrderDetail.setSubTotalAmount(scItemDetailDTO.getSubTotalAmount());
//                        allocateOrderDetail.setExpectedProduceDate(scItemDetailDTO.getExpectedProduceDate());
//                        allocateOrderDetail.setClose(scItemDetailDTO.getClosed());
//                        allocateOrderDetail.setFeatures(scItemDetailDTO.getFeatures());
//                        allocateOrderDetail.setExpectedDeliveryDate(scItemDetailDTO.getExpectedDeliveryDate());
//                        allocateOrderDetail.setOutAllocateApplyOrderLineId(scItemDetailDTO.getOutAllocateApplyOrderLineId());
//                        allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
//                        line ++;
//                    }
//
//                }
//            }
//            responseResponse.setCode(allocateOrderSyncRequest.getCode());
//            return responseResponse;
//        }
//    }

    /**
     * 销售订单 F-B F-b
     * 参数校验
     * 主单创建/更新
     *子单创建/更新
     * 主子单状态计算
     * 调拨预报单的主子单状态计算
     * @param request
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String salesOrderSync(AllocateOrderSalesOrderSyncRequest request) {
        log.info("AllocateOrderWriteRepositoryImpl.salesOrderSync,request:{}", JSON.toJSONString(request));
        AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
        if (request == null) {
            return "请求参数不能为空";
        }
        if (CollectionUtils.isEmpty(request.getAllocateOrderScItemDetails())) {
            return "物料不能为空";
        }
        List<String> collect = request.getAllocateOrderScItemDetails().stream()
                .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode())).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return "物料不能为空";
        }
        //是否是电商调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(request.getReceiveOrgId());
        //电商的调拨单 外部行号不能为空 不能重复
        if (isECommerceOrder){
            List<String> outAllocateLineIdList = request.getAllocateOrderScItemDetails().stream()
                    .map(AllocateOrderScItemDetailDTO::getOutAllocateOrderLineId).distinct()
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(outAllocateLineIdList)){
                return "外部调拨单行号不能为空";
            }
            if (request.getAllocateOrderScItemDetails().size() > outAllocateLineIdList.size()){
                return "外部调拨单行号不能重复";
            }
        }else {
            if (request.getAllocateOrderScItemDetails().size() > collect.size()) {
                return "物料不能重复";
            }
        }

        //2022.04.25 判断这次传递的是否是电商调拨单

        //如果预报单有传递的话
        if (!StringUtils.isAllBlank(request.getOutAllocateApplyOrderId(),request.getAllocateApplyOrderCode())) {
            AllocateApplyOrderLoadListRequest allocateApplyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
            if (StringUtils.isNotBlank(request.getOutAllocateApplyOrderId())){
                allocateApplyOrderLoadListRequest.setOutAllocateApplyOrderId(request.getOutAllocateApplyOrderId());
            }
            if (StringUtils.isNotBlank(request.getAllocateApplyOrderCode())){
                allocateApplyOrderLoadListRequest.setCode(request.getAllocateApplyOrderCode());
            }
            log.info("AllocateOrderWriteRepositoryImpl.salesOrderSync.loadAllocateApplyOrderList,outAllocateApplyOrderId:{}", request.getOutAllocateApplyOrderId());
            Result<List<AllocateApplyOrder>> list = allocateApplyOrderService.loadAllocateApplyOrderList(allocateApplyOrderLoadListRequest);
            log.info("AllocateOrderWriteRepositoryImpl.salesOrderSync.loadAllocateApplyOrderList,outAllocateApplyOrderId:{},loadAllocateApplyOrderListResult:{}", request.getOutAllocateApplyOrderId(), JSON.toJSONString(list));
            if (list != null && CollectionUtils.isNotEmpty(list.getResult())) {
                allocateApplyOrder = list.getResult().get(0);
                if (AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrder.getStatus())) {
                    return "预报单是待推送状态,不允许同步";
                }
            } else {
//                return "未查询到预报单,不允许同步";
            }
        }

        AllocateOrderLoadListRequest orderLoadListRequest = new AllocateOrderLoadListRequest();
        orderLoadListRequest.setOutAllocateOrderId(request.getOutAllocateOrderId());
        orderLoadListRequest.setCode(request.getCode());
        log.info("AllocateOrderWriteRepositoryImpl.salesOrderSync.loadAllocateOrderList,outAllocateOrderId:{}", request.getOutAllocateOrderId());
        Result<List<AllocateOrder>> allocateOrderList = allocateOrderService.loadAllocateOrderList(orderLoadListRequest);

        if (Objects.nonNull(allocateOrderList)&&CollectionUtils.isNotEmpty(allocateOrderList.getResult())){
            request.setCode(allocateOrderList.getResult().get(0).getCode());
        }
        //接下来看 有没有对应的调拨单号
        if (StringUtils.isBlank(request.getCode())) {
            AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
            loadListRequest.setOutAllocateOrderId(request.getOutAllocateOrderId());
            log.info("AllocateOrderWriteRepositoryImpl.salesOrderSync.loadAllocateOrderList,outAllocateOrderId:{}", request.getOutAllocateOrderId());
            Result<List<AllocateOrder>> orderListResult = allocateOrderService.loadAllocateOrderList(loadListRequest);
            log.info("AllocateOrderWriteRepositoryImpl.salesOrderSync.loadAllocateOrderList,outAllocateOrderId:{},loadAllocateOrderListResult:{}", request.getOutAllocateOrderId(), JSON.toJSONString(orderListResult));
            if (orderListResult != null && CollectionUtils.isNotEmpty(orderListResult.getResult())) {
                return "该外部单号已存在,不允许新增";
            }
            //插入
            AllocateOrder allocateOrder = JsonUtil.convert(request, AllocateOrder.class);
            String code = CodeUtil.salesCode();
            allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? request.getReceiveOrgId() : allocateApplyOrder.getApplyOrgId() + "");
            allocateOrder.setCode(code);
            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
            allocateOrder.setAllocateApplyOrderCode(StringUtils.isBlank(allocateApplyOrder.getCode()) ? null : allocateApplyOrder.getCode());
            if (request.getExpectedDeliveryDate() == null) {
                allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
            } else {
                allocateOrder.setExpectedDeliveryDate(request.getExpectedDeliveryDate());
            }
            allocateOrder.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            allocateOrder.setSendBackRequired(false);
            //客户成本中心 采购参考号
            allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
            allocateOrder.setSapCostCenter(request.getSapCostCenter());
            allocateOrder.setOrderReason(request.getOrderReason());
            allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
            allocateOrder.setSapChannel(request.getSapChannel());
            allocateOrder.setProductGroup(request.getProductGroup());
            //如果是空的
            allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId() == null ? request.getReceiveAreaId()
                    : allocateApplyOrder.getReceiveWarehouseId() + "");
            //预调拨单存的是在address上 如果sap传递过来的客户地址id有值就用sap的,因为sap可以直接创建调拨单
            if (StringUtils.isNotBlank(request.getAddressCode())) {
                BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
                batchQueryByIdsRequest.setIdList(Lists.newArrayList(request.getAddressCode()));
                Result<List<CustomerAddress>> listResult = customerAddressService.batchQueryByIds(batchQueryByIdsRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())) {
                    allocateOrder.setCustomerAddressId(request.getAddressCode());
                    CustomerAddress customerAddress = listResult.getResult().get(0);
                    if (customerAddress != null) {
                        allocateOrder.setCustomer(customerAddress.getCustomerCode());
                        allocateOrder.setAddressCode(customerAddress.getAddressCode());
                    }
                }
            } else {
                allocateOrder.setCustomer(allocateApplyOrder.getCustomer());
                allocateOrder.setAddressCode(StringUtils.isBlank(allocateApplyOrder.getCustomerAddress()) ?
                        request.getAddressCode() : allocateApplyOrder.getCustomerAddress());
                allocateOrder.setCustomerAddressId(allocateApplyOrder.getCustomerAddressId());
            }
            //是否工厂直发
            allocateOrder.setIsDTC(allocateApplyOrder.getIsDTC() == null ?
                    (request.getIsDTC() == null ? false : request.getIsDTC()) : allocateApplyOrder.getIsDTC());
            if (Objects.equals(allocateApplyOrder.getIsDTC(), Boolean.TRUE)) {
                allocateOrder.setBranchCustomersCode(allocateApplyOrder.getBranchCustomersCode());
                allocateOrder.setBranchCustomersName(allocateApplyOrder.getBranchCustomersName());
            }
            //如果出入库仓改变的话, 更新一下.
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
            allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
            allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
            WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());
            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
            if (StringUtils.isNotBlank(receiveWmsSDO.getSapSalesOrgId())) {
                allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
            } else {
                //这里如果没有前置预报单据就取对应查询出来的
                allocateOrder.setReceiveOrgId(request.getReceiveOrgId());
            }


            allocateOrder.setConfirmTime(new Date());
            allocateOrder.setSaleChannel(request.getSaleChannel());
            allocateOrder.setSaleDepartmentCode(request.getSaleDepartmentCode());
            if (request.getDocDate() != null) {
                allocateOrder.setDocDate(request.getDocDate());
            } else {
                allocateOrder.setDocDate(InfoUtil.docDate());
            }

            allocateOrder.setReturnOrder("ZRE".equals(request.getOrderType()));
            //工厂直发的要写入收货组织为 客户的组织id  如果收货地址空了再更新
            if (Objects.equals(allocateApplyOrder.getIsDTC(), Boolean.TRUE) && StringUtils.isBlank(allocateOrder.getReceiveOrgId())) {
                if (StringUtils.isNotBlank(allocateApplyOrder.getCustomerAddress())) {
                    AllocateOrderGetCustomerResponse customerByAddressCode = InfoUtil.getCustomerByAddressCode(allocateApplyOrder.getCustomerAddress());
                    if (customerByAddressCode != null && StringUtils.isNotBlank(customerByAddressCode.getSalesOrgId())) {
                        //根据客户获取销售组织id
                        allocateOrder.setReceiveOrgId(customerByAddressCode.getSalesOrgId());
                    }
                }
            }

            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
            if (allocateApplyOrder.getApplyOrgId() == null && StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
//                GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//                getOrganiztionByIdRequest.setId(allocateOrder.getReceiveOrgId());
//                OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//
//
//                if(organiztionById != null && StringUtils.isNotBlank(organiztionById.getParentId())){
//                    allocateOrder.setApplyOrgId(organiztionById.getParentId());
//                }
                OrganizationSDO orgSDO = getOrgSDO(allocateOrder.getReceiveOrgId());
                if (orgSDO != null && Objects.equals(orgSDO.getType(),104)){
                    allocateOrder.setApplyOrgId(orgSDO.getParentId());
                }
            }

            //如果是sap直接创建的
//            if (!Objects.equals(allocateApplyOrder.getIsDTC(), Boolean.TRUE) && Objects.equals(request.getIsDTC(), Boolean.TRUE)) {
//                if (StringUtils.isNotBlank(request.getAddressCode())) {
//                    AllocateOrderGetCustomerResponse customerByAddressCode = InfoUtil.getCustomerByAddressCode(request.getAddressCode());
//                    if (customerByAddressCode != null && StringUtils.isNotBlank(customerByAddressCode.getSalesOrgId())) {
//                        allocateOrder.setReceiveOrgId(customerByAddressCode.getSalesOrgId());
//                        allocateOrder.setCustomer(customerByAddressCode.getCustomer());
//                    }
//                }
//            }
            //如果全关闭
            if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
                boolean allClosed = request.getAllocateOrderScItemDetails().stream()
                        .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
                if (allClosed) {
                    allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
                } else {
                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                }
            }
            allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
            //这一步是为了工厂直发的时候, 电商的收货组织  和普通的收货组织  都是销售组织那一层级
            if(Boolean.TRUE.equals(allocateOrder.getIsDTC())){
                if (StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
                    BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
                    byIds2Request.setIds(Lists.newArrayList(allocateOrder.getReceiveOrgId()));
                    BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
                    if (byIds2Response != null && CollectionUtils.isNotEmpty(byIds2Response.getResult())){
                        OrganizationSDO organizationSDO = byIds2Response.getResult().get(0);
                        Integer type = organizationSDO.getType();
                        //如果是103 那就再往下一层
                        if (Objects.equals(type,103)){
                            GetDownOrganizationListRequest getDownOrganizationListRequest = new GetDownOrganizationListRequest();
                            getDownOrganizationListRequest.setId(organizationSDO.getId());
                            getDownOrganizationListRequest.setType(104);
                            Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> downOrganizationList =
                                    otsPlatformEnhanceService.getDownOrganizationList(getDownOrganizationListRequest);
                            if (downOrganizationList != null && CollectionUtils.isNotEmpty(downOrganizationList.getResult())){
                                String id = downOrganizationList.getResult().get(0).getId();
                                if (StringUtils.isNotBlank(id)){
                                    allocateOrder.setReceiveOrgId(id);
                                }
                            }

                        }
                    }
                }
            }
            //信贷校验状态
            fillCreditCheckStatus(allocateOrder,request.getExt1());
            CreateAllocateOrderResponse response = allocateOrderService.createAllocateOrder(allocateOrder);
            if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
                int line = 1;
                //更新预报单明细的明细数据
                List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
                for (AllocateOrderScItemDetailDTO dto : request.getAllocateOrderScItemDetails()) {
                    AllocateOrderDetail detail = JsonUtil.convert(dto, AllocateOrderDetail.class);
                    detail.setLineNo(line);
                    detail.setOutAllocateOrderLineId(dto.getOutAllocateOrderLineId());
                    detail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
                    detail.setAllocateOrderId(response.getLastInsertId());
                    detail.setAllocateOrderCode(allocateOrder.getCode());
                    detail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
                    detail.setStatus(Objects.equals(dto.getClosed(), Boolean.TRUE) ?
                            AllocateOrderStatus.CLOSED.getValue() :
                            AllocateOrderStatus.Shipment_Processing.getValue());
                    detail.setScItemCode(InfoUtil.subStringScItmCode(dto.getScItemCode()));
                    detail.setUnit(dto.getUnit());
                    detail.setClose(dto.getClosed());
                    detail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
                    detail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
                    detail.setSubTotalAmount(StringUtils.isBlank(dto.getSubTotalAmount()) ? null : dto.getSubTotalAmount().trim());
                    String scItemIdByOutCode = InfoUtil.getScItemIdByOutCode(dto.getScItemCode());
                    if (StringUtils.isBlank(scItemIdByOutCode)){
                        log.error("AllocateOrderWriteRepositoryImpl_salesOrderSync_queryScItemIdError:{},request:{}",dto.getScItemCode(),JSON.toJSONString(request));
                        return dto.getScItemCode() + "货品查询不存在";
                    }
                    detail.setScItemId(scItemIdByOutCode);
//                    detail.setConfirmTime(new Date());
                    handleConfirmTime(detail, dto);
                    detail.setQuantity(InfoUtil.trim(detail.getQuantity()));
                    detail.setConfirmQuantity(InfoUtil.trim(detail.getConfirmQuantity()));
                    detail.setTaxRate(InfoUtil.trim(dto.getTaxRate()));
                    detail.setGiftQuantity(InfoUtil.trim(dto.getGiftQuantity()));
                    detail.setCloseReason(dto.getClosedReason());
                    detail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
                    detail.setDiscountAmount(InfoUtil.trim(dto.getSubTotalAmount()));
                    detail.setCloseCode(dto.getCloseCode());
                    detail.setExpectedProduceDate(dto.getExpectedProduceDate());

                    detail.setRemarks(dto.getRemarks());
                    detail.setGiftQuantity(dto.getGiftQuantity());
                    detail.setTaxRate(dto.getTaxRate());
                    detail.setQuantity(InfoUtil.trim(dto.getQuantity()));
                    detail.setPrice(InfoUtil.trim(dto.getPrice()));
                    allocateOrderDetailService.createAllocateOrderDetail(detail);
                    line++;
                    syncScItemDetails.add(convert2SyncScItemDetail(detail,true,false,
                            dto.getCloseCode(), null,null));
                }

                //调拨单有对应预报单时 同步更新主子单数据
               syncReplyAllocateApplyOrder(allocateApplyOrder,allocateOrder.getCode(),syncScItemDetails);
            }
            return allocateOrder.getCode();
        }
        AllocateOrderLoadListRequest r = new AllocateOrderLoadListRequest();
        r.setCode(request.getCode());
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(r);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return "未查询到该调拨单号";
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
//            if (!Objects.equals(allocateOrder.getOutAllocateOrderId(),request.getOutAllocateOrderId())){
//                return "调拨单号和外部调拨单号关系不匹配";
//            }
        //如果013先于006回调,先把状态改成待发货
        if (Objects.equals(allocateOrder.getStatus(), AllocateOrderStatus.WAIT_PUSH.getValue())) {
            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            if (StringUtils.isNotBlank(request.getOutAllocateOrderId())){
                allocateOrder.setOutAllocateOrderId(request.getOutAllocateOrderId());
            }
            allocateOrderService.updateAllocateOrder(allocateOrder);
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
            allocateOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
                for (AllocateOrderDetail detail : result.getResult()) {
                    if (AllocateOrderStatus.WAIT_PUSH.getValue().equals(detail.getStatus())){
                        detail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        allocateOrderDetailService.updateAllocateOrderDetail(detail);
                    }
                }
            }
//            return "该调拨单未推送成功或回调失败,不允许更新";
        }
        AllocateOrderDetailLoadListRequest checkRequest = new AllocateOrderDetailLoadListRequest();
        checkRequest.setAllocateOrderId(allocateOrder.getId());
        checkRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> checkResult = allocateOrderDetailService.loadAllocateOrderDetailList(checkRequest);
        //22.04.25非电商调拨单 物料编码不允许重复
        if (checkResult != null && CollectionUtils.isNotEmpty(checkResult.getResult()) && !isECommerceOrder) {
            //找出现有的明细; 如果传递的商品有新增的.
            if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
                List<String> scItemCodes = checkResult.getResult().stream()
                        .filter(y -> StringUtils.isNotBlank(y.getScItemCode()))
                        .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode()))
                        .distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(scItemCodes)) {
                    List<String> list = request.getAllocateOrderScItemDetails().stream()
                            .map(z -> InfoUtil.subStringScItmCode(z.getScItemCode())).collect(Collectors.toList());
                    boolean b = scItemCodes.stream().anyMatch(x -> {
                        return !list.contains(x);
                    });
                    if (b) {
                        return "物料编码不允许修改";
                    }
                }
            }
        }

        //校验下sap的明细; 如果物料编码重复了报错;
        set(allocateOrder, request);
        if ("ZRE".equals(request.getOrderType())) {
            allocateOrder.setReturnOrder(true);
        } else {
            allocateOrder.setReturnOrder(false);
        }
        allocateOrder.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
        //如果状态为空时才改状态 涉及数量导致的收发货状态 这边先不处理
        if (allocateOrder.getStatus() == null) {
            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
        }
        allocateOrder.setSapChannel(request.getSapChannel());
        allocateOrder.setProductGroup(request.getProductGroup());
        allocateOrder.setCreateTime(request.getCreateTime());
        //外部主单
        allocateOrder.setOutAllocateOrderId(request.getOutAllocateOrderId());

        if (StringUtils.isNotBlank(request.getSapSalesOrgId())) {
            allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
        }
        if (StringUtils.isNotBlank(request.getSapRefPoNo())) {
            allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
        }
        if (StringUtils.isNotBlank(request.getSapCostCenter())) {
            allocateOrder.setSapCostCenter(request.getSapCostCenter());
        }
        if (StringUtils.isNotBlank(request.getOrderReason())) {
            allocateOrder.setOrderReason(request.getOrderReason());
        }
        if (StringUtils.isNotBlank(request.getAddressCode())) {
            allocateOrder.setAddressCode(StringUtils.isBlank(allocateApplyOrder.getCustomerAddress()) ?
                    request.getAddressCode() : allocateApplyOrder.getCustomerAddress());
        }
//        allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId()==null?null
//                :allocateApplyOrder.getReceiveWarehouseId()+"");
//        //预调拨单存的是在address上
//        allocateOrder.setCustomer(allocateApplyOrder.getCustomerAddress());

        //如果出入库仓改变的话, 更新一下.
        if (StringUtils.isNotBlank(request.getShipAreaId())) {
            allocateOrder.setShipAreaId(request.getShipAreaId());
        }
        //如果有收货仓id
        if (StringUtils.isNotBlank(request.getReceiveAreaId())) {
            allocateOrder.setReceiveAreaId(request.getReceiveAreaId());
        }
        WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
        allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
        allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());
        if (receiveWmsSDO != null) {
            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
            allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
        }
        //如果是sap直接创建的
        if (Objects.equals(allocateOrder.getIsDTC(), Boolean.TRUE) && Objects.equals(request.getIsDTC(), Boolean.TRUE)) {
            if (StringUtils.isNotBlank(request.getAddressCode())) {
                BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
                batchQueryByIdsRequest.setIdList(Lists.newArrayList(request.getAddressCode()));
                Result<List<CustomerAddress>> addressList = customerAddressService.batchQueryByIds(batchQueryByIdsRequest);
                if (addressList != null && CollectionUtils.isNotEmpty(addressList.getResult())) {
                    allocateOrder.setCustomerAddressId(request.getAddressCode());
                    CustomerAddress customerAddress = addressList.getResult().get(0);
                    if (customerAddress != null) {
                        allocateOrder.setCustomer(customerAddress.getCustomerCode());
                        allocateOrder.setAddressCode(customerAddress.getAddressCode());
                        allocateOrder.setReceiveOrgId(request.getReceiveOrgId());
                        //提报组织也改一下.
                        if (StringUtils.isNotBlank(request.getReceiveOrgId())){
                            allocateOrder.setApplyOrgId(request.getReceiveOrgId());
                        }
                    }
                }
//                AllocateOrderGetCustomerResponse customerByAddressCode = InfoUtil.getCustomerByAddressCode(request.getAddressCode());
//                if (customerByAddressCode != null && StringUtils.isNotBlank(customerByAddressCode.getSalesOrgId())){
//                    allocateOrder.setReceiveOrgId(customerByAddressCode.getSalesOrgId());
//                    allocateOrder.setCustomer(customerByAddressCode.getCustomer());
//                }
            }
        }

        //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
        if (allocateApplyOrder.getApplyOrgId() == null && StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
//            GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//            getOrganiztionByIdRequest.setId(allocateOrder.getReceiveOrgId());
//            OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//            if(organiztionById != null && StringUtils.isNotBlank(organiztionById.getParentId())){
//                allocateOrder.setApplyOrgId(organiztionById.getParentId());
//            }
            OrganizationSDO orgSDO = getOrgSDO(allocateOrder.getReceiveOrgId());
            //如果是销售组织这一层的话
            if (orgSDO != null && Objects.equals(orgSDO.getType(),104)){
                allocateOrder.setApplyOrgId(orgSDO.getParentId());
            }
        }

        allocateOrder.setSaleChannel(request.getSaleChannel());
        allocateOrder.setSaleDepartmentCode(request.getSaleDepartmentCode());
        allocateOrder.setGmt_modified(new Date());
        allocateOrder.setDocDate(Optional.ofNullable(request.getDocDate()).orElse(InfoUtil.docDate()));
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
            boolean allClosed = request.getAllocateOrderScItemDetails().stream()
                    .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
            if (allClosed) {
                allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
            } else {
                if (allocateOrder.getStatus() == null) {
                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                }
            }
        }

        //新增一个逻辑
        //这一步是为了工厂直发的时候, 电商的收货组织  和普通的收货组织  都是销售组织那一层级
        if(Boolean.TRUE.equals(allocateOrder.getIsDTC())){
            if (StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
                BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
                byIds2Request.setIds(Lists.newArrayList(allocateOrder.getReceiveOrgId()));
                BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
                if (byIds2Response != null && CollectionUtils.isNotEmpty(byIds2Response.getResult())){
                    OrganizationSDO organizationSDO = byIds2Response.getResult().get(0);
                    Integer type = organizationSDO.getType();
                    //如果是103 那就再往下一层
                    if (Objects.equals(type,103)){
                        GetDownOrganizationListRequest getDownOrganizationListRequest = new GetDownOrganizationListRequest();
                        getDownOrganizationListRequest.setId(organizationSDO.getId());
                        getDownOrganizationListRequest.setType(104);
                        Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> downOrganizationList =
                                otsPlatformEnhanceService.getDownOrganizationList(getDownOrganizationListRequest);
                        if (downOrganizationList != null && CollectionUtils.isNotEmpty(downOrganizationList.getResult())){
                            String id = downOrganizationList.getResult().get(0).getId();
                            if (StringUtils.isNotBlank(id)){
                                allocateOrder.setReceiveOrgId(id);
                            }
                        }

                    }
                }
            }
        }
        if (StringUtils.isBlank(allocateOrder.getAllocateApplyOrderId()) && allocateApplyOrder.getId() != null){
            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId().toString());
        }
        if (StringUtils.isBlank(allocateOrder.getAllocateApplyOrderCode()) && StringUtils.isNotBlank(allocateApplyOrder.getCode())){
            allocateOrder.setAllocateApplyOrderCode(allocateApplyOrder.getCode());
        }
        //设置调拨单的信贷校验信息
        fillCreditCheckStatus(allocateOrder,request.getExt1());
        UpdateAllocateOrderResponse updateAllocateOrderResponse = allocateOrderService.updateAllocateOrder(allocateOrder);
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
            //获取最大的行号
            AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            detailLoadListRequest.setAllocateOrderCode(request.getCode());
            detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> rr = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
            int line = 1;
            Set<Boolean> flag = Sets.newHashSet();
            if (rr != null && CollectionUtils.isNotEmpty(rr.getResult())) {
//                String lines = rr.getResult().stream().filter(Objects::nonNull).filter(orderDetail -> StringUtils.isNotBlank(orderDetail.getLineNo()))
//                        .max(Comparator.comparing(AllocateOrderDetail::getLineNo)).get().getLineNo();
//                if (StringUtils.isNotBlank(lines))line = Integer.parseInt(lines);

                List<Integer> lineList = rr.getResult().stream().filter(Objects::nonNull).
                        filter(orderDetail -> orderDetail.getLineNo() != null)
                        .map(AllocateOrderDetail::getLineNo).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(lineList)) {
                    Integer max = Collections.max(lineList);
                    if (max != null) {
                        line = max;
                    }
                }

            }

            //开始更改调拨单明细状态
            List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
            for (AllocateOrderScItemDetailDTO dto : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetailLoadListRequest loadListRequest = new AllocateOrderDetailLoadListRequest();
                loadListRequest.setAllocateOrderCode(request.getCode());
//                    loadListRequest.setOutAllocateOrderLineId(dto.getOutAllocateOrderLineId());
                String scItemId = InfoUtil.getScItemIdByOutCode(dto.getScItemCode());
                if (StringUtils.isBlank(scItemId)){
                    log.error("AllocateOrderWriteRepositoryImpl_salesOrderSync_queryScItemIdError:{},request:{}",dto.getScItemCode(),JSON.toJSONString(request));
                    return dto.getScItemCode() + "货品查询不存在";
                }
                loadListRequest.setScItemId(scItemId);//根据这个货品id来查询了.
                //22.04.25 电商调拨单明细使用行号来确定物料行
                if (isECommerceOrder){
                    loadListRequest.setScItemId(null);
                    loadListRequest.setOutAllocateOrderLineId(dto.getOutAllocateOrderLineId());
                }
                String oldQuantity = null;
                Boolean oldAllocateClosed = false;
                String oldConfirmQuantity = null;
                Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(loadListRequest);
                if (isECommerceOrder){
                    if (result == null || CollectionUtils.isEmpty(result.getResult()) && StringUtils.isNotBlank(dto.getLineNo())){
                        loadListRequest.setScItemId(null);
                        loadListRequest.setOutAllocateOrderLineId(null);
                        loadListRequest.setLineNo(Integer.valueOf(dto.getLineNo()));
                        result = allocateOrderDetailService.loadAllocateOrderDetailList(loadListRequest);
                    }
                }
                if (result == null || CollectionUtils.isEmpty(result.getResult())) {
                    AllocateOrderDetail orderDetail = new AllocateOrderDetail();
                    convert(orderDetail, dto);
                    orderDetail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
                    orderDetail.setAllocateOrderCode(request.getCode());
                    orderDetail.setAllocateOrderId(allocateOrder.getId());
                    orderDetail.setLineNo(line + 1);
                    orderDetail.setProductGroup(request.getProductGroup());
                    orderDetail.setUnit(dto.getUnit());
                    orderDetail.setTaxRate(dto.getTaxRate());
                    orderDetail.setGiftQuantity(dto.getGiftQuantity());
                    orderDetail.setRemarks(dto.getRemarks());
                    orderDetail.setPrice(InfoUtil.trim(dto.getPrice()));
                    orderDetail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
                    orderDetail.setClose(dto.getClosed());
                    orderDetail.setProductGroup(dto.getProductGroup());
                    orderDetail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
                    orderDetail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
                    orderDetail.setQuantity(InfoUtil.trim(dto.getQuantity()));
                    orderDetail.setConfirmQuantity(InfoUtil.trim(dto.getConfirmQuantity()));
                    orderDetail.setGiftQuantity(InfoUtil.trim(dto.getGiftQuantity()));
                    orderDetail.setTaxRate(InfoUtil.trim(dto.getTaxRate()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
                    orderDetail.setScItemId(scItemId);
                    handleConfirmTime(orderDetail, dto);
                    orderDetail.setCloseReason(StringUtils.isBlank(dto.getClosedReason()) ? "" : dto.getClosedReason());
                    orderDetail.setDiscountAmount(InfoUtil.trim(dto.getSubTotalAmount()));
                    orderDetail.setExpectedProduceDate(dto.getExpectedProduceDate());
                    if (Objects.equals(Boolean.TRUE, dto.getClosed())) {
                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    }
                    allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
                    line++;
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,true,false,
                            orderDetail.getCloseCode() ,null,null));
                } else {
                    AllocateOrderDetail orderDetail = result.getResult().get(0);
                    oldQuantity = orderDetail.getQuantity();
                    oldAllocateClosed=orderDetail.getClose() == null? false : orderDetail.getClose();
                    oldConfirmQuantity = orderDetail.getConfirmQuantity();
                    convert(orderDetail, dto);
                    orderDetail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
                    orderDetail.setProductGroup(request.getProductGroup());
                    orderDetail.setUnit(dto.getUnit());
                    orderDetail.setTaxRate(dto.getTaxRate());
                    orderDetail.setRemarks(dto.getRemarks());
                    orderDetail.setPrice(dto.getPrice());
                    orderDetail.setClose(dto.getClosed());
                    orderDetail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
                    orderDetail.setProductGroup(dto.getProductGroup());
                    orderDetail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
                    orderDetail.setPrice(dto.getPrice());
                    orderDetail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
                    orderDetail.setScItemId(scItemId);
//                    orderDetail.setScItemId(InfoUtil.getScItemIdByOutCode(dto.getScItemCode()));
                    orderDetail.setQuantity(InfoUtil.trim(dto.getQuantity()));
                    orderDetail.setConfirmQuantity(InfoUtil.trim(dto.getConfirmQuantity()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
                    orderDetail.setDiscountAmount(InfoUtil.trim(dto.getSubTotalAmount()));
                    orderDetail.setCloseReason(StringUtils.isBlank(dto.getClosedReason()) ? "" : dto.getClosedReason());
                    orderDetail.setExpectedProduceDate(dto.getExpectedProduceDate());
                    if (Objects.equals(dto.getClosed(), Boolean.TRUE)) {
                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    } else if (Objects.equals(orderDetail.getStatus(), AllocateOrderStatus.CLOSED.getValue())) {
                        orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                    }
                    handleConfirmTime(orderDetail, dto);

                    orderDetail.setGmt_modified(new Date());
                    sapUpdateLineStatus(orderDetail);
                    if (StringUtils.isNotBlank(dto.getGiftQuantity())){
                        orderDetail.setGiftQuantity(dto.getGiftQuantity().trim());
                    }
//                    Integer giftQuantity = SapAndCrmFieldDealUtils.toInteger(dto.getGiftQuantity());
//                    if (Objects.nonNull(giftQuantity)) {
//                        orderDetail.setGiftQuantity(giftQuantity.toString());
//                    }
                    allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
                    //组装更新预报单明细的数据
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,false,
                            oldAllocateClosed, dto.getCloseCode(),
                            oldQuantity,oldConfirmQuantity));
                }
            }
            //同步更新回复预报单
            syncReplyAllocateApplyOrder(allocateApplyOrder,allocateOrder.getCode(),syncScItemDetails);
            AllocateOrderDetailLoadListRequest endRequest = new AllocateOrderDetailLoadListRequest();
            endRequest.setAllocateOrderId(allocateOrder.getId());
            //查出全部子单
            endRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> endList = allocateOrderDetailService.loadAllocateOrderDetailList(endRequest);
            sapUpdateOrderStatus(endList, allocateOrder);
        }
        return allocateOrder.getCode();

    }

    // --------- 保留下  ------------
//    public String salesOrderSync(AllocateOrderSalesOrderSyncRequest request) {
//        AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
//        if (request == null){
//            // TODO: 2021/12/2 余红伟 定义一些常量
//            return "请求参数不能为空";
//        }
//        if (CollectionUtils.isEmpty(request.getAllocateOrderScItemDetails())){
//            return "物料不能为空";
//        }
//        List<String> collect = request.getAllocateOrderScItemDetails().stream()
//                .map(x-> InfoUtil.deleteZeroPrefix(x.getScItemCode())).distinct().collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(collect)){
//            return "物料不能为空";
//        }
//        if (request.getAllocateOrderScItemDetails().size() > collect.size()){
//            return "物料不能重复";
//        }
//        //如果预报单有传递的话
//        if (StringUtils.isNotBlank(request.getOutAllocateApplyOrderId())){
//            AllocateApplyOrderLoadListRequest allocateApplyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
//            allocateApplyOrderLoadListRequest.setOutAllocateApplyOrderId(request.getOutAllocateApplyOrderId());;
//            Result<List<AllocateApplyOrder>> list = allocateApplyOrderService.loadAllocateApplyOrderList(allocateApplyOrderLoadListRequest);
//            if (list != null && CollectionUtils.isNotEmpty(list.getResult())){
//                allocateApplyOrder = list.getResult().get(0);
//                if (AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrder.getStatus())){
//                    return "预报单是待推送状态,不允许同步";
//                }
//            }
//        }
//        //接下来看 有没有对应的调拨单号
//        if (StringUtils.isBlank(request.getCode())){
//            AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
//            loadListRequest.setOutAllocateOrderId(request.getOutAllocateOrderId());
//            Result<List<AllocateOrder>> orderListResult = allocateOrderService.loadAllocateOrderList(loadListRequest);
//            if (orderListResult != null && CollectionUtils.isNotEmpty(orderListResult.getResult())){
//                return "该外部单号已存在,不允许新增";
//            }
//            //插入
//            AllocateOrder allocateOrder = JsonUtil.convert(request,AllocateOrder.class);
//            String code = CodeUtil.salesCode();
//            allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId()==null?null:allocateApplyOrder.getApplyOrgId()+"");
//            allocateOrder.setCode(code);
//            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId()==null?null:allocateApplyOrder.getId() +"");
//            allocateOrder.setAllocateApplyOrderCode(StringUtils.isBlank(allocateApplyOrder.getCode())?null:allocateApplyOrder.getCode());
//            if (request.getExpectedDeliveryDate() == null){
//                allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
//            }else {
//                allocateOrder.setExpectedDeliveryDate(request.getExpectedDeliveryDate());
//            }
//            allocateOrder.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
//            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//            allocateOrder.setSendBackRequired(false);
//            //客户成本中心 采购参考号
//            allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
//            allocateOrder.setSapCostCenter(request.getSapCostCenter());
//            allocateOrder.setOrderReason(request.getOrderReason());
//            allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
//            allocateOrder.setSapChannel(request.getSapChannel());
//            allocateOrder.setProductGroup(request.getProductGroup());
//            //如果是空的
//            allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId()==null?null
//                    :allocateApplyOrder.getReceiveWarehouseId()+"");
//            //预调拨单存的是在address上
//            allocateOrder.setCustomer(allocateApplyOrder.getCustomer());
//            allocateOrder.setAddressCode(allocateApplyOrder.getCustomerAddress());
//            //是否工厂直发
//            allocateOrder.setIsDTC(allocateApplyOrder.getIsDTC() == null?false:allocateApplyOrder.getIsDTC());
//            if(Objects.equals(allocateApplyOrder.getIsDTC(),Boolean.TRUE)){
//                allocateOrder.setBranchCustomersCode(allocateApplyOrder.getBranchCustomersCode());
//                allocateOrder.setBranchCustomersName(allocateApplyOrder.getBranchCustomersName());
//            }
//            //如果出入库仓改变的话, 更新一下.
//            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
//            allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
//            allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
//            WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());
//            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
//            allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
//            allocateOrder.setConfirmTime(new Date());
//            allocateOrder.setSaleChannel(request.getSaleChannel());
//            allocateOrder.setSaleDepartmentCode(request.getSaleDepartmentCode());
//            if (request.getDocDate() != null){
//                allocateOrder.setDocDate(request.getDocDate());
//            }else {
//                allocateOrder.setDocDate(InfoUtil.docDate());
//            }
//
//
//            if ("ZRE".equals(request.getOrderType())){
//                allocateOrder.setReturnOrder(true);
//            }else {
//                allocateOrder.setReturnOrder(false);
//            }
//            //工厂直发的要写入收货组织为 客户的组织id
//            if (Objects.equals(allocateApplyOrder.getIsDTC(),Boolean.TRUE)){
//                if (StringUtils.isNotBlank(allocateApplyOrder.getCustomerAddress())){
//                    AllocateOrderGetCustomerResponse customerByAddressCode = InfoUtil.getCustomerByAddressCode(allocateApplyOrder.getCustomerAddress());
//                    if (customerByAddressCode != null && StringUtils.isNotBlank(customerByAddressCode.getSalesOrgId())){
//                        //根据客户获取销售组织id
//                        allocateOrder.setReceiveOrgId(customerByAddressCode.getSalesOrgId());
//                    }
//                }
//            }
//            //如果全关闭
//            if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())){
//                boolean allClosed = request.getAllocateOrderScItemDetails().stream()
//                        .allMatch(x->Objects.equals(Boolean.TRUE,x.getClosed()));
//                if (allClosed){
//                    allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                }else {
//                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                }
//            }
//            allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
//            CreateAllocateOrderResponse response = allocateOrderService.createAllocateOrder(allocateOrder);
//            if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())){
//                int line = 1;
//                for (AllocateOrderScItemDetailDTO dto : request.getAllocateOrderScItemDetails()){
//                    AllocateOrderDetail detail = JsonUtil.convert(dto,AllocateOrderDetail.class);
//                    detail.setLineNo(line +"");
//                    detail.setOutAllocateOrderLineId(dto.getOutAllocateOrderLineId());
//                    detail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
//                    detail.setAllocateOrderId(response.getLastInsertId());
//                    detail.setAllocateOrderCode(allocateOrder.getCode());
//                    detail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
//                    detail.setStatus( Objects.equals(dto.getClosed(),Boolean.TRUE)?
//                            AllocateOrderStatus.CLOSED.getValue():
//                            AllocateOrderStatus.Shipment_Processing.getValue());
//                    detail.setScItemCode(InfoUtil.deleteZeroPrefix(dto.getScItemCode()));
//                    detail.setUnit(dto.getUnit());
//                    detail.setClose(dto.getClosed());
//                    detail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
//                    detail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
//                    detail.setSubTotalAmount(StringUtils.isBlank(dto.getSubTotalAmount())?null:dto.getSubTotalAmount().trim());
//                    detail.setScItemId(InfoUtil.getScItemIdByOutCode(dto.getScItemCode()));
////                    detail.setConfirmTime(new Date());
//                    handleConfirmTime(detail,dto);
//                    detail.setQuantity(InfoUtil.trim(detail.getQuantity()));
//                    detail.setConfirmQuantity(InfoUtil.trim(detail.getConfirmQuantity()));
//                    detail.setTaxRate(InfoUtil.trim(dto.getTaxRate()));
//                    detail.setGiftQuantity(InfoUtil.trim(dto.getGiftQuantity()));
//                    detail.setCloseReason(dto.getClosedReason());
//                    detail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
//                    detail.setDiscountAmount(InfoUtil.trim(dto.getSubTotalAmount()));
//                    detail.setCloseCode(dto.getCloseCode());
//                    //加入预报单的行号
//                    if (allocateApplyOrder != null && allocateApplyOrder.getId() != null){
//                        AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest = new AllocateApplyOrderDetailLoadListRequest();
//                        allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrder.getId().intValue());
//                        allocateApplyOrderDetailLoadListRequest.setGoodsId(detail.getScItemId());
//                        Result<List<AllocateApplyOrderDetail>> listResult = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
//                        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
//                            AllocateApplyOrderDetail allocateApplyOrderDetail = listResult.getResult().get(0);
//                            detail.setAllocateApplyOrderLineId(allocateApplyOrderDetail.getLineNo()==null?null:allocateApplyOrderDetail.getLineNo()+"");
//                            allocateApplyOrderDetail.setIsClosed(dto.getClosed()?1:0);
//                            if (Objects.equals(dto.getClosed(),Boolean.TRUE)){
//                                allocateApplyOrderDetail.setStatus(AllocateStatusEnum.CLOSED.getCode());
//                                allocateApplyOrderDetail.setCloseReason(dto.getCloseCode());
//                                allocateApplyOrderDetail.setCloseCode(dto.getCloseCode());
//                            }else {
//                                Integer v = InfoUtil.addReply(allocateApplyOrderDetail.getReplyQuantity(),dto.getQuantity());
//                                Integer amount = allocateApplyOrderDetail.getApplyQuantity() == null?0:allocateApplyOrderDetail.getApplyQuantity();
//                                allocateApplyOrderDetail.setReplyQuantity(v);
//
//                                //修改预报单的确认数量
//                                Integer c = InfoUtil.addReply(allocateApplyOrderDetail.getConfirmQuantity(),dto.getConfirmQuantity());
//                                allocateApplyOrderDetail.setConfirmQuantity(c);
//                                if (amount <= v){
//                                    allocateApplyOrderDetail.setStatus(AllocateStatusEnum.COMPLETED.getCode());
//                                }else {
//                                    //判断如果是跨公司类型状态不改变，其他类型状态改为部分回复
//                                    if (!DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrder.getType().toString())){
//                                        allocateApplyOrderDetail.setStatus(AllocateStatusEnum.PART_ANSWER.getCode());
//                                    }
//                                }
//                            }
//                            allocateApplyOrderDetail.setGmt_modified(new Date());
//                            allocateApplyOrderDetail.setReplyDate(new Date());
//                            //生产日期
//                            allocateApplyOrderDetail.setProductionTime(dto.getExpectedProduceDate());
//                            allocateApplyOrderDetailService.updateAllocateApplyOrderDetail(allocateApplyOrderDetail);
//                        }
//                    }
//                    detail.setRemarks(dto.getRemarks());
//                    detail.setGiftQuantity(dto.getGiftQuantity());
//                    detail.setTaxRate(dto.getTaxRate());
//                    detail.setQuantity(InfoUtil.trim(dto.getQuantity()));
//                    detail.setPrice(InfoUtil.trim(dto.getPrice()));
//                    allocateOrderDetailService.createAllocateOrderDetail(detail);
//                    line ++;
//                }
//
//                //更改主单的状态
//                //查询预调拨单详情
//                List<AllocateApplyOrderGoodsDetailDTO> list = allocateApplyOrderDetailReadRepository.loadDetailByOrderId(allocateApplyOrder.getId());
//                if (CollectionUtils.isNotEmpty(list)){
//                    boolean isStatus = true;
//                    for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO:list){
//                        if (!AllocateApplyOrderStatusEnum.COMPLETED.getCode().equals(allocateApplyOrderGoodsDetailDTO.getStatus())&&!AllocateApplyOrderStatusEnum.CLOSED.getCode().equals(allocateApplyOrderGoodsDetailDTO.getStatus())){
//                            isStatus = false;
//                        }
//                    }
//                    if (isStatus){
//                        allocateApplyOrder.setStatus(AllocateStatusEnum.COMPLETED.getCode());
//                        //完成时间
//                        allocateApplyOrder.setCompleteTime(new Date());
//                    }else {
//                        //判断如果是跨公司类型状态不改变，其他类型状态改为部分回复
//                        if (!DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrder.getType().toString())){
//                            allocateApplyOrder.setStatus(AllocateStatusEnum.PART_ANSWER.getCode());
//                        }
//                    }
//                    allocateApplyOrder.setGmt_modified(new Date());
//                    allocateApplyOrderService.updateAllocateApplyOrder(allocateApplyOrder);
//                }
//            }
////            AllocateOrderSalesOrderSyncResponse re =new AllocateOrderSalesOrderSyncResponse();
////            re.setCode(allocateOrder.getCode());
//            //TODO 应该还有其他操作 例如销售单接口 退单之类的
//            return code;
//        }
//        AllocateOrderLoadListRequest r = new AllocateOrderLoadListRequest();
//        r.setCode(request.getCode());
//        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(r);
//        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
//            return "未查询到该调拨单号";
//        }
//        AllocateOrder allocateOrder = listResult.getResult().get(0);
////            if (!Objects.equals(allocateOrder.getOutAllocateOrderId(),request.getOutAllocateOrderId())){
////                return "调拨单号和外部调拨单号关系不匹配";
////            }
//        if (Objects.equals(allocateOrder.getStatus(),AllocateOrderStatus.WAIT_PUSH.getValue())){
//            return "该调拨单未推送成功或回调失败,不允许更新";
//        }
//        set(allocateOrder,request);
//        if ("ZRE".equals(request.getOrderType())){
//            allocateOrder.setReturnOrder(true);
//        }else {
//            allocateOrder.setReturnOrder(false);
//        }
//        allocateOrder.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
//        allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//        allocateOrder.setSapChannel(request.getSapChannel());
//        allocateOrder.setProductGroup(request.getProductGroup());
//        allocateOrder.setCreateTime(request.getCreateTime());
//        //外部主单
//        allocateOrder.setOutAllocateOrderId(request.getOutAllocateOrderId());
//
//        if (StringUtils.isNotBlank(request.getSapSalesOrgId())){
//            allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
//        }
//        if (StringUtils.isNotBlank(request.getSapRefPoNo())){
//            allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
//        }
//        if (StringUtils.isNotBlank(request.getSapCostCenter())){
//            allocateOrder.setSapCostCenter(request.getSapCostCenter());
//        }
//        if (StringUtils.isNotBlank(request.getOrderReason())){
//            allocateOrder.setOrderReason(request.getOrderReason());
//        }
////        allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId()==null?null
////                :allocateApplyOrder.getReceiveWarehouseId()+"");
////        //预调拨单存的是在address上
////        allocateOrder.setCustomer(allocateApplyOrder.getCustomerAddress());
//
//        //如果出入库仓改变的话, 更新一下.
//        if (StringUtils.isNotBlank(request.getShipAreaId())){
//            allocateOrder.setShipAreaId(request.getShipAreaId());
//        }
//        WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
//        allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
//        allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
//        WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());
//        allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
//        allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
//
//        allocateOrder.setSaleChannel(request.getSaleChannel());
//        allocateOrder.setSaleDepartmentCode(request.getSaleDepartmentCode());
//        allocateOrder.setGmt_modified(new Date());
//        allocateOrder.setDocDate(Optional.ofNullable(request.getDocDate()).orElse(InfoUtil.docDate()));
//        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())){
//            boolean allClosed = request.getAllocateOrderScItemDetails().stream()
//                    .allMatch(x->Objects.equals(Boolean.TRUE,x.getClosed()));
//            if (allClosed){
//                allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
//            }else {
//                allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//            }
//        }
//        UpdateAllocateOrderResponse updateAllocateOrderResponse = allocateOrderService.updateAllocateOrder(allocateOrder);
//        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())){
//            //获取最大的行号
//            AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
//            detailLoadListRequest.setAllocateOrderCode(request.getCode());
//            Result<List<AllocateOrderDetail>> rr = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
//            int line = 1;
//            Set<Boolean> flag = Sets.newHashSet();
//            if (rr != null && CollectionUtils.isNotEmpty(rr.getResult())){
//                String lines = rr.getResult().stream().filter(Objects::nonNull).filter(orderDetail -> StringUtils.isNotBlank(orderDetail.getLineNo()))
//                        .max(Comparator.comparing(AllocateOrderDetail::getLineNo)).get().getLineNo();
//                if (StringUtils.isNotBlank(lines))line = Integer.parseInt(lines);
//            }
//
//            for (AllocateOrderScItemDetailDTO dto : request.getAllocateOrderScItemDetails()){
//                AllocateOrderDetailLoadListRequest loadListRequest = new AllocateOrderDetailLoadListRequest();
//                loadListRequest.setAllocateOrderCode(request.getCode());
////                    loadListRequest.setOutAllocateOrderLineId(dto.getOutAllocateOrderLineId());
//                String scItemId = InfoUtil.getScItemIdByOutCode(dto.getScItemCode());
//                loadListRequest.setScItemId(scItemId);//根据这个货品id来查询了.
//                String oldQuantity = null;
//                String oldConfirmQuantity = null;
//                Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(loadListRequest);
//                if (result == null || CollectionUtils.isEmpty(result.getResult())) {
//                    AllocateOrderDetail orderDetail = new AllocateOrderDetail();
//                    convert(orderDetail,dto);
//                    orderDetail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
//                    orderDetail.setAllocateOrderCode(request.getCode());
//                    orderDetail.setAllocateOrderId(allocateOrder.getId() +"");
//                    orderDetail.setLineNo((line +1) +"");
//                    orderDetail.setProductGroup(request.getProductGroup());
//                    orderDetail.setUnit(dto.getUnit());
//                    orderDetail.setTaxRate(dto.getTaxRate());
//                    orderDetail.setGiftQuantity(dto.getGiftQuantity());
//                    orderDetail.setRemarks(dto.getRemarks());
//                    orderDetail.setPrice(InfoUtil.trim(dto.getPrice()));
//                    orderDetail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
//                    orderDetail.setClose(dto.getClosed());
//                    orderDetail.setProductGroup(dto.getProductGroup());
//                    orderDetail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
//                    orderDetail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
//                    orderDetail.setQuantity(InfoUtil.trim(dto.getQuantity()));
//                    orderDetail.setConfirmQuantity(InfoUtil.trim(dto.getConfirmQuantity()));
//                    orderDetail.setGiftQuantity(InfoUtil.trim(dto.getGiftQuantity()));
//                    orderDetail.setTaxRate(InfoUtil.trim(dto.getTaxRate()));
//                    orderDetail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
//                    orderDetail.setScItemId(scItemId);
//                    handleConfirmTime(orderDetail,dto);
//                    orderDetail.setCloseReason(StringUtils.isBlank(dto.getClosedReason())?"":dto.getClosedReason());
//                    orderDetail.setDiscountAmount(InfoUtil.trim(dto.getSubTotalAmount()));
//                    if (Objects.equals(Boolean.TRUE,dto.getClosed())){
//                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                    }
//
//                    //加入预报单的行号
//                    if (allocateApplyOrder != null && allocateApplyOrder.getId() != null){
//                        AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest = new AllocateApplyOrderDetailLoadListRequest();
//                        allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrder.getId().intValue());
//                        allocateApplyOrderDetailLoadListRequest.setGoodsId(orderDetail.getScItemId());
//                        Result<List<AllocateApplyOrderDetail>> listResult1 = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
//                        if (listResult1 != null && CollectionUtils.isNotEmpty(listResult1.getResult())){
//                            AllocateApplyOrderDetail allocateApplyOrderDetail = listResult1.getResult().get(0);
//                            orderDetail.setAllocateApplyOrderLineId(allocateApplyOrderDetail.getLineNo()==null?null:allocateApplyOrderDetail.getLineNo()+"");
//                            allocateApplyOrderDetail.setIsClosed(dto.getClosed()?1:0);
//                            if (Objects.equals(dto.getClosed(),Boolean.TRUE)){
//                                allocateApplyOrderDetail.setStatus(AllocateStatusEnum.CLOSED.getCode());
//                                allocateApplyOrderDetail.setCloseReason(dto.getCloseCode());
//                                allocateApplyOrderDetail.setCloseCode(dto.getCloseCode());
//                            }else {
//                                Integer v = InfoUtil.addReply(allocateApplyOrderDetail.getReplyQuantity(),dto.getQuantity());
//                                Integer amount = allocateApplyOrderDetail.getApplyQuantity() == null?0:allocateApplyOrderDetail.getApplyQuantity();
//                                allocateApplyOrderDetail.setReplyQuantity(v);
//
//                                //确认数量
//                                Integer c = InfoUtil.addReply(allocateApplyOrderDetail.getConfirmQuantity(),dto.getConfirmQuantity());
//                                allocateApplyOrderDetail.setConfirmQuantity(c);
//                                if (amount <= v){
//                                    allocateApplyOrderDetail.setStatus(AllocateStatusEnum.COMPLETED.getCode());
//                                }else {
//                                    //判断如果是跨公司类型状态不改变，其他类型状态改为部分回复
//                                    if (!DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrder.getType().toString())){
//                                        allocateApplyOrderDetail.setStatus(AllocateStatusEnum.PART_ANSWER.getCode());
//                                    }
//                                }
//                                allocateApplyOrderDetail.setCloseCode("");
//                                allocateApplyOrderDetail.setCloseReason("");
//                            }
//                            allocateApplyOrderDetail.setGmt_modified(new Date());
//                            allocateApplyOrderDetail.setReplyDate(new Date());
//                            //生产日期
//                            allocateApplyOrderDetail.setProductionTime(dto.getExpectedProduceDate());
//                            allocateApplyOrderDetailService.updateAllocateApplyOrderDetail(allocateApplyOrderDetail);
//                        }
//                    }
//
//
//
//                    allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
//                    line++;
//                }else {
//                    AllocateOrderDetail orderDetail = result.getResult().get(0);
//                    oldQuantity = orderDetail.getQuantity();
//                    oldConfirmQuantity = orderDetail.getConfirmQuantity();
//                    convert(orderDetail,dto);
//                    orderDetail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
//                    orderDetail.setProductGroup(request.getProductGroup());
//                    orderDetail.setUnit(dto.getUnit());
//                    orderDetail.setTaxRate(dto.getTaxRate());
//                    orderDetail.setRemarks(dto.getRemarks());
//                    orderDetail.setPrice(dto.getPrice());
//                    orderDetail.setClose(dto.getClosed());
//                    orderDetail.setExpectedDeliveryDate(dto.getExpectedDeliveryDate());
//                    orderDetail.setProductGroup(dto.getProductGroup());
//                    orderDetail.setOutAllocateApplyOrderLineId(dto.getOutAllocateApplyOrderLineId());
//                    orderDetail.setPrice(dto.getPrice());
//                    orderDetail.setAllocateApplyOrderLineId(dto.getAllocateApplyOrderLineId());
//                    orderDetail.setScItemId(InfoUtil.getScItemIdByOutCode(dto.getScItemCode()));
//                    orderDetail.setQuantity(InfoUtil.trim(dto.getQuantity()));
//                    orderDetail.setConfirmQuantity(InfoUtil.trim(dto.getConfirmQuantity()));
//                    orderDetail.setSubTotalAmount(InfoUtil.trim(dto.getSubTotalAmount()));
//                    orderDetail.setDiscountAmount(InfoUtil.trim(dto.getSubTotalAmount()));
//                    orderDetail.setCloseReason(StringUtils.isBlank(dto.getClosedReason())?"":dto.getClosedReason());
//                    if (Objects.equals(dto.getClosed(),Boolean.TRUE)){
//                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                    }
//                    handleConfirmTime(orderDetail,dto);
//
//
//                    //加入预报单的行号
//                    if (allocateApplyOrder != null && allocateApplyOrder.getId() != null){
//                        AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest = new AllocateApplyOrderDetailLoadListRequest();
//                        allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrder.getId().intValue());
//                        allocateApplyOrderDetailLoadListRequest.setGoodsId(orderDetail.getScItemId());
//                        Result<List<AllocateApplyOrderDetail>> listResult1 = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
//                        if (listResult1 != null && CollectionUtils.isNotEmpty(listResult1.getResult())){
//                            AllocateApplyOrderDetail allocateApplyOrderDetail = listResult1.getResult().get(0);
//                            orderDetail.setAllocateApplyOrderLineId(allocateApplyOrderDetail.getLineNo()==null?null:allocateApplyOrderDetail.getLineNo()+"");
//                            allocateApplyOrderDetail.setIsClosed(dto.getClosed()?1:0);
//                            if (Objects.equals(dto.getClosed(),Boolean.TRUE)){
//                                allocateApplyOrderDetail.setStatus(AllocateStatusEnum.CLOSED.getCode());
//                                allocateApplyOrderDetail.setCloseReason(dto.getCloseCode());
//                                allocateApplyOrderDetail.setCloseCode(dto.getCloseCode());
//                            }else {
//                                String difference = InfoUtil.getDifference(oldQuantity, dto.getQuantity());
//                                Integer v = InfoUtil.addReply(allocateApplyOrderDetail.getReplyQuantity(),difference);
////                                    Integer v = InfoUtil.addReply(allocateApplyOrderDetail.getReplyQuantity(),dto.getQuantity());
//                                Integer amount = allocateApplyOrderDetail.getApplyQuantity() == null?0:allocateApplyOrderDetail.getApplyQuantity();
//                                allocateApplyOrderDetail.setReplyQuantity(v);
//
//                                //确认数量修改
//                                String differenceConfirmQuantity = InfoUtil.getDifference(oldConfirmQuantity,dto.getConfirmQuantity());
//                                Integer c = InfoUtil.addReply(allocateApplyOrderDetail.getConfirmQuantity(),differenceConfirmQuantity);
//                                allocateApplyOrderDetail.setConfirmQuantity(c);
//
//                                if (amount <= v){
//                                    allocateApplyOrderDetail.setStatus(AllocateStatusEnum.COMPLETED.getCode());
//                                }else {
//                                    //判断如果是跨公司类型状态不改变，其他类型状态改为部分回复
//                                    if (!DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrder.getType().toString())){
//                                        allocateApplyOrderDetail.setStatus(AllocateStatusEnum.PART_ANSWER.getCode());
//                                    }
//                                }
//                                allocateApplyOrderDetail.setCloseReason("");
//                                allocateApplyOrderDetail.setCloseCode("");
//                            }
//                            allocateApplyOrderDetail.setGmt_modified(new Date());
//                            allocateApplyOrderDetail.setReplyDate(new Date());
//                            //生产日期
//                            allocateApplyOrderDetail.setProductionTime(dto.getExpectedProduceDate());
//                            allocateApplyOrderDetailService.updateAllocateApplyOrderDetail(allocateApplyOrderDetail);
//                        }
//                    }
//                    orderDetail.setGmt_modified(new Date());
//                    allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
//                }
//                //更改主单的状态
//                //查询预调拨单详情
//                List<AllocateApplyOrderGoodsDetailDTO> list = allocateApplyOrderDetailReadRepository.loadDetailByOrderId(allocateApplyOrder.getId());
//                if (CollectionUtils.isNotEmpty(list)){
//                    boolean isStatus = true;
//                    for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO:list){
//                        if (!AllocateApplyOrderStatusEnum.COMPLETED.getCode().equals(allocateApplyOrderGoodsDetailDTO.getStatus())&&!AllocateApplyOrderStatusEnum.CLOSED.getCode().equals(allocateApplyOrderGoodsDetailDTO.getStatus())){
//                            isStatus = false;
//                        }
//                    }
//                    //判断状态 修改主单状态
//                    if (isStatus){
//                        allocateApplyOrder.setStatus(AllocateStatusEnum.COMPLETED.getCode());
//                        //完成时间
//                        allocateApplyOrder.setCompleteTime(new Date());
//                    }else {
//                        //判断如果是跨公司类型状态不改变，其他类型状态改为部分回复
//                        if (!DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrder.getType().toString())){
//                            allocateApplyOrder.setStatus(AllocateStatusEnum.PART_ANSWER.getCode());
//                        }
//                    }
//                    allocateApplyOrder.setGmt_modified(new Date());
//                    allocateApplyOrderService.updateAllocateApplyOrder(allocateApplyOrder);
//                }
//
//            }
//        }
//        return allocateOrder.getCode();
//
//    }

    /**
     * 平台回复生成调拨单
     *
     * @param request
     * @return
     */
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @Override
    @RepositoryInvoker(printLog = true)
    public String create(AllocateOrderCreateRequest request) {
        if (StringUtils.isBlank(request.getAllocateApplyOrderId())) {
            throw new FacadeException("OTS-03-005-00-15-007");
        }
        LoadAllocateApplyOrderRequest loadAllocateApplyOrderRequest = new LoadAllocateApplyOrderRequest();
        loadAllocateApplyOrderRequest.setId(request.getAllocateApplyOrderId());
        AllocateApplyOrder allocateApplyOrder = allocateApplyOrderService.loadAllocateApplyOrder(loadAllocateApplyOrderRequest);
        if (allocateApplyOrder == null) {
            throw new FacadeException("OTS-03-005-00-15-008");
        }
        if (allocateApplyOrder.getType() == null) {
            throw new FacadeException("OTS-03-005-00-15-009");
        }
        if (CollectionUtils.isEmpty(request.getAllocateOrderScItemDetails())) {
            throw new FacadeException("OTS-03-005-00-15-021");
        }
        //平台回复生成调拨单 如果是关闭行 就不生成调拨单
        List<AllocateOrderScItemDetailDTO> collect = request.getAllocateOrderScItemDetails().stream()
                .filter(x -> !Objects.equals(x.getClosed(), Boolean.TRUE)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            // TODO: 2021/12/2 return null 代表什么含义，成功还是失败 余红伟
//            throw new FacadeException("OTS-03-005-00-15-021");
            return null;
        }
        request.setAllocateOrderScItemDetails(collect);

        AllocateOrder allocateOrder = new AllocateOrder();
        allocateOrder.setAllocateApplyOrderId(request.getAllocateApplyOrderId());
        allocateOrder.setAllocateApplyOrderCode(request.getAllocateApplyOrderCode());
        allocateOrder.setSapCostCenter(allocateApplyOrder.getSapCostCenter());

        allocateOrder.setOrderReason(allocateApplyOrder.getReason());
        allocateOrder.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
        allocateOrder.setFounder(allocateApplyOrder.getCreator());
        allocateOrder.setBeginDate(allocateApplyOrder.getTakeEffectTime());
        allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
        allocateOrder.setCompleteTime(allocateApplyOrder.getCompleteTime());
        allocateOrder.setShipAreaId(allocateApplyOrder.getShipWarehouseId() == null ? null : allocateApplyOrder.getShipWarehouseId() + "");
        allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId() == null ? null : allocateApplyOrder.getReceiveWarehouseId() + "");
        //查询逻辑仓上的仓库档案 组织信息
        WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
        WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());

        allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
        allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
        allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());

        allocateOrder.setProductGroup(allocateApplyOrder.getGoodsGroup() == null ? null : allocateApplyOrder.getGoodsGroup() + "");
//        allocateOrder.setOutAllocateOrderId(request.getOutAllocateOrderId());
        allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
        //  创建调拨单的时候 需要让预报单回复时传递对应的渠道和组织编码
//        allocateOrder.setSapChannel(allocateApplyOrder.getSaleChannel());
        allocateOrder.setSapChannel(allocateApplyOrder.getHeadquartersChannelCode());
        allocateOrder.setSapSalesOrgId(allocateApplyOrder.getHeadquartersOrganizationCode());
//        allocateOrder.setSapSalesOrgId(allocateApplyOrder.getSaleOrganizationCode());
        //TODO  还需要个客户编码 地址编码
        allocateOrder.setCustomer(allocateApplyOrder.getCustomer());
        allocateOrder.setAddressCode(allocateApplyOrder.getCustomerAddress());
        allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
        String code = CodeUtil.getCode(allocateApplyOrder.getType());
        allocateOrder.setCode(code);
//        allocateOrder.setReturnOrder(Objects.equals(allocateApplyOrder.getReturnGood(),1)?true:false);
        allocateOrder.setReturnOrder(false);
        allocateOrder.setType(allocateApplyOrder.getType());

//        allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
        //现在都改成待推送.
        allocateOrder.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
        allocateOrder.setCreateTime(new Date());
        allocateOrder.setLastUpdateUser(NameUtil.getRealName(allocateApplyOrder.getCreator()));
//        allocateOrder.setDocDate(allocateApplyOrder.getOrderTime());
        allocateOrder.setDocDate(InfoUtil.docDate());
        allocateOrder.setShipMethod(allocateApplyOrder.getShipMethod() == null ? null : Integer.parseInt(allocateApplyOrder.getShipMethod()));
        allocateOrder.setRemark(allocateApplyOrder.getRemark());
        // TODO 是否还货这个  需要确认
//        allocateOrder.setSendBackRequired(allocateApplyOrder.);
        allocateOrder.setSendBackRequired(request.getSendBackRequired() == null ? true : false);
        allocateOrder.setIsDTC(allocateApplyOrder.getIsDTC() == null ? false : allocateApplyOrder.getIsDTC());
        allocateOrder.setConfirmTime(new Date());
        allocateOrder.setBranchCustomersCode(allocateApplyOrder.getBranchCustomersCode());
        allocateOrder.setBranchCustomersName(allocateApplyOrder.getBranchCustomersName());

        allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
        CreateAllocateOrderResponse createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);
        if (createAllocateOrderResponse == null || createAllocateOrderResponse.getLastInsertId() == null) {
            // TODO: 2021/12/2 统一改成log 余红伟
            throw new FacadeException("OTS-03-005-00-15-006");
        }
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
            int i = 1;
            for (AllocateOrderScItemDetailDTO detailDTO : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail orderDetail = new AllocateOrderDetail();
                //是否还货 根据预报单的查询
                if (allocateApplyOrder != null) {
                    AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest =
                            new AllocateApplyOrderDetailLoadListRequest();
                    allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId().intValue());
                    allocateApplyOrderDetailLoadListRequest.setGoodsId(detailDTO.getScItemId());
                    Result<List<AllocateApplyOrderDetail>> listResult =
                            allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
                    if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())) {
                        orderDetail.setSendBackRequired("1".equals(listResult.getResult().get(0).getSendBackRequired()) ? true : false);
                    }
                }

                if (detailDTO.getExpectedDeliveryDate() != null) {
                    orderDetail.setExpectedDeliveryDate(detailDTO.getExpectedDeliveryDate());
                } else {
                    orderDetail.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
                }
                orderDetail.setOutAllocateApplyOrderLineId(detailDTO.getOutAllocateApplyOrderLineId());
                orderDetail.setSubTotalAmount(detailDTO.getSubTotalAmount());
                orderDetail.setDiscountAmount(detailDTO.getSubTotalAmount());
                orderDetail.setRemarks(detailDTO.getRemarks());
                orderDetail.setAllocateOrderCode(allocateOrder.getCode());
//                orderDetail.setInvoiceLineNo(detailD);
                orderDetail.setDeliveryQuantity(detailDTO.getDeliveryQuantity());
                orderDetail.setFeatures(detailDTO.getFeatures());
                orderDetail.setType(allocateOrder.getType());
                orderDetail.setQuantity(StringUtils.isBlank(detailDTO.getQuantity()) ? null : detailDTO.getQuantity().trim());
                orderDetail.setScItemId(detailDTO.getScItemId());
                orderDetail.setLineNo(i);
                orderDetail.setClose(detailDTO.getClosed());
//                orderDetail.setUnit(detailDTO.getUnit());
                orderDetail.setUnit(InfoUtil.getUnitByOutCode(detailDTO.getScItemCode()));
                orderDetail.setConfirmQuantity(StringUtils.isBlank(detailDTO.getConfirmQuantity()) ? orderDetail.getQuantity() : detailDTO.getConfirmQuantity().trim());
                orderDetail.setGiftQuantity(StringUtils.isBlank(detailDTO.getGiftQuantity()) ? null : detailDTO.getGiftQuantity().trim());
                orderDetail.setExpectedProduceDate(detailDTO.getExpectedProduceDate());
//                orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                orderDetail.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());//待推送
                orderDetail.setCloseReason(detailDTO.getClosedReason());
                orderDetail.setProductGroup(detailDTO.getProductGroup());
                orderDetail.setAllocateOrderId(createAllocateOrderResponse.getLastInsertId());
                orderDetail.setOutAllocateOrderLineId(detailDTO.getOutAllocateOrderLineId());
//                orderDetail.setAllocateApplyOrderLineId(detailDTO.getAllocateApplyOrderLineId());
                orderDetail.setAllocateApplyOrderLineId(detailDTO.getAllocateApplyOrderLineNo());
                orderDetail.setScItemCode(detailDTO.getScItemCode());
//                orderDetail.setUnit(InfoUtil.getUnit(detailDTO.getScItemId()));
                orderDetail.setApplyQuantity(StringUtils.isBlank(detailDTO.getApplyQuantity()) ? null : Long.parseLong(detailDTO.getApplyQuantity().trim()));
                orderDetail.setReplyQuantity(StringUtils.isBlank(detailDTO.getReplyQuantity()) ? null : Long.parseLong(detailDTO.getReplyQuantity().trim()));
                orderDetail.setPrice(StringUtils.isBlank(detailDTO.getPrice()) ? null : detailDTO.getPrice().trim());
                orderDetail.setCreator(NameUtil.getRealName(detailDTO.getCreator()));
                orderDetail.setReturnOrder(allocateOrder.getReturnOrder());
                orderDetail.setConfirmTime(new Date());
                orderDetail.setIsDTC(allocateOrder.getIsDTC());
                orderDetail.setExchangeAmt(InfoUtil.trim(detailDTO.getExchangeAmt()));
//                orderDetail.setScItemCode(InfoUtil.deleteZeroPrefix(allocateApplyOrder));
                allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
                i++;
            }
        }

        return String.valueOf(createAllocateOrderResponse.getLastInsertId());
    }

    private Date strToDate(String dateString){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.parse(dateString);
        } catch (Exception e) {
            log.error("AllocateOrderWriteRepository.date.strToDate 转换异常:{}",e);
        }
        return null;
    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String createAllocateOrderApi(AllocateOrderCreateRequest request) {
        if (CollectionUtils.isEmpty(request.getAllocateOrderScItemDetails())) {
            throw new FacadeException("OTS-03-005-00-15-021");
        }
        AllocateOrder allocateOrder = new AllocateOrder();
        allocateOrder.setBusinessType(request.getBusinessType());
        allocateOrder.setProductGroup(request.getBusinessType());
        allocateOrder.setFromSys(request.getFromSys());
        allocateOrder.setReturnOrder(request.getReturnOrder());
        allocateOrder.setReceiveWarehouseId(request.getReceiveWareHouseId());
        allocateOrder.setShipWarehouseId(request.getShipWareHouseId());
        allocateOrder.setDocDate(strToDate(request.getDocDate()));
        allocateOrder.setExpectedDeliveryDate(request.getExpectedDeliveryDate());
        allocateOrder.setShipMethod(request.getShipMethod());
        allocateOrder.setRemark(request.getRemark());
        // -------
        allocateOrder.setAllocateApplyOrderId(request.getAllocateApplyOrderId());
        allocateOrder.setAllocateApplyOrderCode(request.getAllocateApplyOrderCode());
        allocateOrder.setSapCostCenter(request.getSapCostCenter());
//        allocateOrder.setOrderReason(allocateApplyOrder.getReason());
        allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
//        allocateOrder.setFounder(allocateApplyOrder.getCreator());
//        allocateOrder.setReturnOrder(request.getReturnOrder());
//        allocateOrder.setBeginDate(allocateApplyOrder.getTakeEffectTime());
//        allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
//        allocateOrder.setCompleteTime(allocateApplyOrder.getCompleteTime());
//        allocateOrder.setShipAreaId(allocateApplyOrder.getShipWarehouseId() == null ? null : allocateApplyOrder.getShipWarehouseId() + "");
//        allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId() == null ? null : allocateApplyOrder.getReceiveWarehouseId() + "");
        //查询逻辑仓上的仓库档案 组织信息
        Map<String, WmsSDO> wmsSDOMap = InfoUtil.getWmsSDOMapByAreaList(Lists.newArrayList(request.getShipAreaId(), request.getReceiveAreaId()));
        WmsSDO shipWmsSDO = wmsSDOMap.get(request.getShipAreaId());
        WmsSDO receiveWmsSDO = wmsSDOMap.get(request.getReceiveAreaId());
        //features 收发货仓的工厂编码和库存地点
        Map<String,String> featuresMap = Maps.newHashMap();
        featuresMap.put(FeaturesKey.DELIVERY_FACTORY_CODE,shipWmsSDO.getFactoryCode());
        featuresMap.put(FeaturesKey.DELIVERY_STORAGE_LOCATION_CODE,shipWmsSDO.getInventoryCode());
        featuresMap.put(FeaturesKey.RECEIVE_FACTORY_CODE,receiveWmsSDO.getFactoryCode());
        featuresMap.put(FeaturesKey.RECEIVE_STORAGE_LOCATION_CODE,receiveWmsSDO.getInventoryCode());
        allocateOrder.setShipAreaId(request.getShipAreaId());
        allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
        allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        allocateOrder.setReceiveAreaId(request.getReceiveAreaId());
        allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
        allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
        allocateOrder.setProductGroup(request.getProductGroup() == null ? "11" : request.getProductGroup());
//        allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
        //  创建调拨单的时候 需要让预报单回复时传递对应的渠道和组织编码
//        allocateOrder.setSapChannel(allocateApplyOrder.getHeadquartersChannelCode());
//        allocateOrder.setSapSalesOrgId(allocateApplyOrder.getHeadquartersOrganizationCode());
        //TODO  还需要个客户编码 地址编码
//        allocateOrder.setCustomer(allocateApplyOrder.getCustomer());
//        allocateOrder.setAddressCode(allocateApplyOrder.getCustomerAddress());
        allocateOrder.setApplyOrgId(request.getApplyOrgId());
        String code = CodeUtil.getCode(request.getType());
        allocateOrder.setCode(code);
        allocateOrder.setType(request.getType());
        if (StringUtils.isNotBlank(request.getBizFeatures())){
            featuresMap.putAll(FeatureUtil.fromString(request.getBizFeatures()));
        }
        if (MapUtils.isNotEmpty(featuresMap)) {
            allocateOrder.setBizFeatures(FeatureUtil.toString(featuresMap));
        }

//        //现在都改成待推送.
//        allocateOrder.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
        Integer statusValue = AllocateOrderStatus.DRAFT.getValue();
        // submitFlag:true提交（待推送），false不提交（草稿）
        if(request.getSubmitFlag()){
            statusValue = AllocateOrderStatus.WAIT_PUSH.getValue();
        }
        allocateOrder.setStatus(statusValue);
        allocateOrder.setCreateTime(new Date());
//        allocateOrder.setLastUpdateUser(NameUtil.getRealName(allocateApplyOrder.getCreator()));
//        allocateOrder.setDocDate(InfoUtil.docDate());
//        allocateOrder.setShipMethod(allocateApplyOrder.getShipMethod() == null ? null : Integer.parseInt(allocateApplyOrder.getShipMethod()));
//        allocateOrder.setRemark(request.getRemark());
        // TODO 是否还货这个  需要确认
        allocateOrder.setSendBackRequired(request.getSendBackRequired() == null ? true : false);
        allocateOrder.setIsDTC( false);
        allocateOrder.setConfirmTime(new Date());
//        allocateOrder.setBranchCustomersCode(allocateApplyOrder.getBranchCustomersCode());
//        allocateOrder.setBranchCustomersName(allocateApplyOrder.getBranchCustomersName());

        allocateOrder.setRequestId(request.getRequestId());
        allocateOrder.setThirdAllocateOrderId(request.getThirdAllocateOrderId());
        allocateOrder.setFeatures(request.getFeatures());

        allocateOrder.setAllocateApplyOrderId(request.getAllocateApplyOrderId());
        allocateOrder.setRelatedAllocateOrderCode(request.getRelatedAllocateOrderCode());
        allocateOrder.setFulfillmentTypeCode(request.getFulfillmentTypeCode());
        if (CollectionUtils.isNotEmpty(request.getOrderTag())) {
            allocateOrder.setOrderTag(StringUtils.join(request.getOrderTag().toArray(),","));
        }
        allocateOrder.setAutoFulfillment(Integer.valueOf(1).equals(request.getAutoFulfillment()));
        if (StringUtils.isNotBlank(request.getTakeEffectDate())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                allocateOrder.setBeginDate(sdf.parse(request.getTakeEffectDate()));
            } catch (ParseException e) {
                throw new FacadeException("10031","生效日期格式错误");
            }
        }
        allocateOrder.setShipMethod(request.getShipMethod());
        allocateOrder.setThirdAllocateOrderId(request.getThirdAllocateOrderId());
        allocateOrder.setRelatedAllocateOrderCode(request.getRelatedAllocateOrderCode());
        allocateOrder.setPriority(request.getPriority());
        allocateOrder.setTransferWarehouseId(request.getTransferWarehouseId());
        //创建人名称
        allocateOrder.setCreatorName(request.getCreatorName());
        allocateOrder.setModifierName(request.getCreatorName());

        CreateAllocateOrderResponse createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);
        if (createAllocateOrderResponse == null || createAllocateOrderResponse.getLastInsertId() == null) {
            // TODO: 2021/12/2 统一改成log 余红伟
            throw new FacadeException("OTS-03-005-00-15-006");
        }
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
            int i = 1;
            for (AllocateOrderScItemDetailDTO detailDTO : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail orderDetail = new AllocateOrderDetail();
                //是否还货 根据预报单的查询
//                if (allocateApplyOrder != null) {
//                    AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest =
//                            new AllocateApplyOrderDetailLoadListRequest();
//                    allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId().intValue());
//                    allocateApplyOrderDetailLoadListRequest.setGoodsId(detailDTO.getScItemId());
//                    Result<List<AllocateApplyOrderDetail>> listResult =
//                            allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
//                    if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())) {
//                        orderDetail.setSendBackRequired("1".equals(listResult.getResult().get(0).getSendBackRequired()) ? true : false);
//                    }
//                }
                orderDetail.setScItemId(detailDTO.getScItemId());
                orderDetail.setQuantity(StringUtils.isBlank(detailDTO.getQuantity()) ? null : detailDTO.getQuantity().trim());
                orderDetail.setUnit(detailDTO.getUnit());
                orderDetail.setExpectedProduceDate(StringUtils.isNotBlank(detailDTO.getProductDate()) ? strToDate(detailDTO.getProductDate()) : null);
                orderDetail.setRemarks(detailDTO.getRemark());
                orderDetail.setOutAllocateApplyOrderLineId(detailDTO.getOutAllocateApplyOrderLineId());
                orderDetail.setExpectedDeliveryDate(request.getExpectedDeliveryDate());
                orderDetail.setScItemName(detailDTO.getTitle());
//                orderDetail.setExpectedDeliveryDate(request.getExpectedDeliveryDate());
                orderDetail.setSubTotalAmount(detailDTO.getSubTotalAmount());
                orderDetail.setDiscountAmount(detailDTO.getSubTotalAmount());
                orderDetail.setAllocateOrderCode(allocateOrder.getCode());
                orderDetail.setDeliveryQuantity(detailDTO.getDeliveryQuantity());
                orderDetail.setFeatures(detailDTO.getFeatures());
                orderDetail.setType(allocateOrder.getType());
                orderDetail.setLineNo(i);
                orderDetail.setClose(Boolean.TRUE.equals(detailDTO.getClosed()));
                orderDetail.setUnit("PC");
                //调拨单创
                orderDetail.setConfirmQuantity(StringUtils.isBlank(detailDTO.getConfirmQuantity()) ? null : detailDTO.getConfirmQuantity().trim());
                orderDetail.setGiftQuantity(StringUtils.isBlank(detailDTO.getGiftQuantity()) ? null : detailDTO.getGiftQuantity().trim());
                orderDetail.setStatus(statusValue);//待推送
                orderDetail.setCloseReason(detailDTO.getClosedReason());
                orderDetail.setProductGroup(detailDTO.getProductGroup());
                orderDetail.setAllocateOrderId(createAllocateOrderResponse.getLastInsertId());
                orderDetail.setOutAllocateOrderLineId(detailDTO.getOutAllocateOrderLineId());
                orderDetail.setAllocateApplyOrderLineId(detailDTO.getAllocateApplyOrderLineNo());
                orderDetail.setScItemCode(detailDTO.getScItemCode());
                orderDetail.setApplyQuantity(StringUtils.isBlank(detailDTO.getApplyQuantity()) ? null : Long.parseLong(detailDTO.getApplyQuantity().trim()));
                orderDetail.setReplyQuantity(StringUtils.isBlank(detailDTO.getReplyQuantity()) ? null : Long.parseLong(detailDTO.getReplyQuantity().trim()));
                orderDetail.setPrice(StringUtils.isBlank(detailDTO.getPrice()) ? null : detailDTO.getPrice().trim());
                orderDetail.setReturnOrder(allocateOrder.getReturnOrder());
                orderDetail.setConfirmTime(new Date());
                orderDetail.setIsDTC(allocateOrder.getIsDTC());
                orderDetail.setExchangeAmt(InfoUtil.trim(detailDTO.getExchangeAmt()));

                orderDetail.setThirdLineNo(detailDTO.getThirdLineNo());
                orderDetail.setRelatedAllocateSubOrderId(detailDTO.getRelatedAllocateSubOrderId());
                if (StringUtils.isNotBlank(detailDTO.getBizFeatures())){
                    orderDetail.setBizFeatures(detailDTO.getBizFeatures());
                }
                orderDetail.setCreatorName(request.getCreatorName());
                orderDetail.setModifierName(request.getCreatorName());
                allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
                i++;
            }
        }
        return String.valueOf(createAllocateOrderResponse.getLastInsertId());
    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String create(AllocateOrderSDO allocateOrderSDO) {

        AllocateOrder allocateOrder = JSONObject.parseObject(JSON.toJSONString(allocateOrderSDO),
                AllocateOrder.class);
        CreateAllocateOrderResponse response =
                allocateOrderService.createAllocateOrder(allocateOrder);
        return String.valueOf(response.getLastInsertId());
    }

    public AllocateOrder convert(AllocateOrderSDO allocateOrderSDO) {
        AllocateOrder allocateOrder = JSONObject.parseObject(JSON.toJSONString(allocateOrderSDO),
                AllocateOrder.class);
        return allocateOrder;
    }

    /**
     * F-F1 sap->ots 创建/更新
     *
     * @param allocateOrderSDO
     * @return
     */
    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @Deprecated
    public String sync(AllocateOrderSDO allocateOrderSDO) {
        AllocateOrder allocateOrder = JSONObject.parseObject(JSON.toJSONString(allocateOrderSDO),
                AllocateOrder.class);
        CreateAllocateOrderResponse response =
                allocateOrderService.createAllocateOrder(allocateOrder);
        return String.valueOf(response.getLastInsertId());
    }

    /**
     * F-F1 sap->ots 创建/更新
     *
     * @param allocateOrderSDO
     * @return
     */
    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @Deprecated
    public String sync(AllocateOrderSDO allocateOrderSDO, List<AllocateOrderDetailSDO> detailSDOS) {
        //先查一次预报单
        AllocateApplyOrderLoadListRequest request = new AllocateApplyOrderLoadListRequest();
        request.setCode(allocateOrderSDO.getAllocateApplyOrderId());
        Result<List<AllocateApplyOrder>> applyResult =
                allocateApplyOrderService.loadAllocateApplyOrderList(request);
        if (applyResult == null || CollectionUtils.isEmpty(applyResult.getResult())) {
            // TODO: 2021/12/2 日志通过log来记录，另外return null代表什么含义，成功还是失败？
            System.out.println("没有找到对应的预报单...");
            return null;
        }
        AllocateApplyOrder allocateApplyOrder = applyResult.getResult().get(0);
        //如果有调拨单code了 update
        if (StringUtils.isNotBlank(allocateOrderSDO.getCode())) {
            AllocateOrderLoadListRequest r = new AllocateOrderLoadListRequest();
            r.setCode(allocateOrderSDO.getCode());
            Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(r);
            if (result == null || CollectionUtils.isEmpty(result.getResult())) {
                return null;
            }
            AllocateOrder allocateOrder = result.getResult().get(0);
//            allocateOrder.setAllocateApplyOrderCode(allocateOrderSDO.getCode());
            set(allocateOrder, allocateOrderSDO);
            allocateOrder.setGmt_modified(new Date());
            allocateOrderService.updateAllocateOrder(allocateOrder);
            if (CollectionUtils.isNotEmpty(detailSDOS)) {
                for (AllocateOrderDetailSDO detailSDO : detailSDOS) {
                    AllocateOrderDetailUpdateRequest updateRequest = JsonUtil.convert(detailSDO, AllocateOrderDetailUpdateRequest.class);
                    updateRequest.setAllocateOrderId(Long.valueOf(detailSDO.getAllocateOrderId()));
                    allocateOrderDetailService.syncUpdate(updateRequest);
                }
            }
            return allocateOrderSDO.getCode();

        } else {
            //如果code是空的
            AllocateOrder allocateOrder = JsonUtil.convert(allocateOrderSDO, AllocateOrder.class);
            String code = CodeUtil.getCode(allocateOrderSDO.getType());
            allocateOrder.setCode(code);
            allocateOrder.setGmt_create(null);
            allocateOrder.setGmt_modified(null);
            allocateOrder.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
//            allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getInvalidDate());
//            allocateOrder.setCreateTime(null);
            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
            allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
            CreateAllocateOrderResponse response = allocateOrderService.createAllocateOrder(allocateOrder);
            if (CollectionUtils.isNotEmpty(detailSDOS)) {
                Long allocateOrderId = response.getLastInsertId();
                for (AllocateOrderDetailSDO sdo : detailSDOS) {
                    AllocateOrderDetail detail = JsonUtil.convert(sdo, AllocateOrderDetail.class);
                    detail.setAllocateOrderCode(code);
                    detail.setAllocateOrderId(allocateOrderId);
                    allocateOrderDetailService.createAllocateOrderDetail(detail);
                }
            }
            return code;

        }
    }

    public WmsSDO getWmsSDO(String areaId) {
        if (StringUtils.isNotBlank(areaId)) {
            QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
            queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(areaId));
            QueryCargoZoneByIdResponse shipAreaQuery = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
            return getWmsSDO(shipAreaQuery);
        }
        return new WmsSDO();
    }

    public static WmsSDO getWmsSDO(QueryCargoZoneByIdResponse response) {
        WmsSDO wmsSDO = new WmsSDO();
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())) {
            JSONArray array = JSON.parseArray(JSON.toJSONString(response.getResult()));
            if (array != null && array.size() > 0) {
                JSONObject data = array.getJSONObject(0);
//                wmsSDO.setInventoryCode(data.getString("code"));
                wmsSDO.setInventoryCode(data.getString("warehouseCode"));
                wmsSDO.setFactoryCode(data.getString("sapFactoryCode"));
                wmsSDO.setSapCompanyCode(data.getString("sapCompanyCode"));
                wmsSDO.setSapSalesBPCode(data.getString("sapSaleBPCode"));//有点问题的.
                wmsSDO.setSapDeliveryBPCode(data.getString("sapDeliveryBPCode"));
                wmsSDO.setSapInternalDeliveryBPCode(data.getString("sapInternalDeliveryBPCode"));
                wmsSDO.setSapInternalSalesBPCode(data.getString("sapInternalSalesBPCode"));
                wmsSDO.setSapSalesOrgId(data.getString("saleOrgId"));
//                wmsSDO.setSapSalesOrgId(data.getString("sapSaleOrgId"));
                wmsSDO.setName(data.getString("name"));
                wmsSDO.setType(data.getString("type"));
                wmsSDO.setWarehouseId(data.getString("warehouseId"));

//                if (StringUtils.isNotBlank(data.getString("features"))){
//                    JSONObject features = JSON.parseObject(data.getString("features"));
//                    if (features != null){
//                        wmsSDO.setSapCompanyCode(features.getString(""));
//                    }
//                }
            }
        }
        return wmsSDO;
    }

    /**
     * PC 手动创建  F1-B
     *
     * @param request
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderResponse manualCreate(AllocateOrderManualCreateRequest request) {
        // TODO: 2021/12/2 把模型转换封装成一个converter 余红伟 万文洋
        AllocateOrder allocateOrder = new AllocateOrder();
        String code = CodeUtil.salesCode();
//        code = CodeUtil.getCode();
        allocateOrder.setCode(code);
        allocateOrder.setIsDTC(request.getIsDTC() == null ? false : request.getIsDTC());
        allocateOrder.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
        allocateOrder.setApplyOrgId(request.getApplyOrgId());
        //货品组编码 要传递给他们想要的 例如 11
        allocateOrder.setProductGroup(StringUtils.isBlank(request.getProductGroup()) ? "11" : request.getProductGroup().trim());
        allocateOrder.setReturnOrder(request.getReturnOrder() == null ? false : request.getReturnOrder());
        allocateOrder.setShipAreaId(request.getShipAreaId());
//        allocateOrder.setShipWarehouseId(StringUtils.isBlank(request.getShipWarehouseId()));
        allocateOrder.setReceiveAreaId(request.getReceiveAreaId());
        allocateOrder.setReceiveWarehouseId(request.getReceiveWarehouseId());
        WmsSDO shipWmsSDO = getWmsSDO(request.getShipAreaId());
        WmsSDO receiveWmsSDO = getWmsSDO(request.getReceiveAreaId());
        if (shipWmsSDO != null) {
            allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
            allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        }
        if (receiveWmsSDO != null) {
//            allocateOrder.setCustomer(receiveWmsSDO.getSapDeliveryBPCode());
            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
            allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
        }
        if (StringUtils.isNotBlank(request.getShipMethod())) {
            allocateOrder.setShipMethod(Integer.parseInt(request.getShipMethod()));
        }
//        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(request.getExpectedDeliveryTime()));
        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(request.getExpectedDeliveryTime()));
        if (request.getDocDate() == null) {
            allocateOrder.setDocDate(InfoUtil.salesDocDate());
        } else {
//            allocateOrder.setDocDate(TimeUtil.parseSimpleDateFormat(request.getDocDate()));
            allocateOrder.setDocDate(TimeUtil.parseYYYY_MM_dd(request.getDocDate()));
            if (allocateOrder.getDocDate() == null) {
                allocateOrder.setDocDate(InfoUtil.salesDocDate());
            }
        }
        if (StringUtils.isBlank(request.getExpectedDeliveryTime())){
            allocateOrder.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(request.getExpectedDeliveryTime()));
        }else {
            allocateOrder.setExpectedDeliveryDate(InfoUtil.afterDays(allocateOrder.getDocDate(),1));
        }
//        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(request.getExpectedDeliveryTime()));

        allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
        allocateOrder.setSapCostCenter(request.getSapCostCenter());
        allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
        allocateOrder.setSapChannel(request.getSapChannel());
        //F1-B 不存客户
//        allocateOrder.setCustomer(request.getCustomer());
        allocateOrder.setAddressCode(request.getAddressCode());
        //总部客户地址 选择不存?
        allocateOrder.setStatus(AllocateOrderStatus.DRAFT.getValue());
        allocateOrder.setRemark(request.getRemark());
        allocateOrder.setOrderReason(request.getOrderReason());
        allocateOrder.setSendBackRequired(false);
        allocateOrder.setIsDTC(false);


        //获取仓库信息
        Map<String, JSONObject> warehouseIdMap = new HashMap<>();
        //仓库id集合
        Set<String> warehouseIds = new HashSet<>();
        warehouseIds.add(request.getReceiveAreaId() == null ? null : request.getReceiveAreaId());
        warehouseIds.add(request.getShipAreaId());
        BatchQueryWarehouseByIdsRequest batchQueryWarehouseByIdsRequest = new BatchQueryWarehouseByIdsRequest();
        batchQueryWarehouseByIdsRequest.setWarehouseIds(new ArrayList(warehouseIds));
        batchQueryWarehouseByIdsRequest.setModelList(Lists.newArrayList(1, 3, 5));
        Object data = unifiedInventoryService.batchQueryWarehouseByIds(batchQueryWarehouseByIdsRequest);
        if (Objects.nonNull(data)) {
            JSONObject js = JSON.parseObject(JSON.toJSONString(data));
            if (Objects.nonNull(js)) {
                JSONArray array = js.getJSONArray("result");
                if (Objects.nonNull(array) && array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        if (Objects.nonNull(object)) {
                            warehouseIdMap.put(object.getString("id"), object);
                        }
                    }
                }
            }
        }
        //校验收发货仓编码 权限问题
        JSONObject receiveWarehouseCodeJson = warehouseIdMap.get(request.getReceiveAreaId() == null ? null : request.getReceiveAreaId());
        JSONObject shipWarehouseCodeJson = warehouseIdMap.get(request.getShipAreaId());

        String receiveWarehouseCode = null;
        String shipWarehouseCode = null;
        if (Objects.nonNull(receiveWarehouseCodeJson)) {
            receiveWarehouseCode = receiveWarehouseCodeJson.getString("code");
        }
        if (Objects.nonNull(shipWarehouseCodeJson)) {
            shipWarehouseCode = shipWarehouseCodeJson.getString("code");
        }
        WarehouseBaseInfo warehouseInfo = checkWarehouse(receiveWarehouseCode, shipWarehouseCode, 2, 0);

        if (Objects.isNull(warehouseInfo) || StringUtils.isEmpty(warehouseInfo.getReceiveWarehouseId())) {
            throw new FacadeException("OTS-03-005-00-15-088");
        }
        if (Objects.isNull(warehouseInfo) || StringUtils.isEmpty(warehouseInfo.getDeliveryWarehouseId())) {
            throw new FacadeException("OTS-03-005-00-15-089");
        }

        //判断时间是否正确
        //单据日期
        if (Objects.nonNull(request.getDocDate())) {
            if (!isDateError(request.getDocDate())) {
                throw new FacadeException("OTS-03-005-00-15-080");
            }
        }

        //期待交货日期
        if (Objects.nonNull(request.getExpectedDeliveryDate())) {
            if (!isDateError(request.getExpectedDeliveryDate())) {
                throw new FacadeException("OTS-03-005-00-15-083");
            }
        }


        CreateAllocateOrderResponse response = allocateOrderService.createAllocateOrder(allocateOrder);

        LoadAllocateOrderRequest loadAllocateOrderRequest = new LoadAllocateOrderRequest();
        loadAllocateOrderRequest.setId(String.valueOf(response.getLastInsertId()));
        AllocateOrder order = allocateOrderService.loadAllocateOrder(loadAllocateOrderRequest);
        // 这个客户不应该存在.
//        AllocateOrderGetCustomerResponse customerResponse = getCustomer(order.getCustomer());

        AllocateOrderResponse orderResponse = new AllocateOrderResponse();
        orderResponse.setId(order.getId() + "");
        orderResponse.setCode(code);
        orderResponse.setType(order.getType() == null ? null : order.getType().toString());
        orderResponse.setTypeDesc(getTypeDesc(order.getType()));
        orderResponse.setStatus(order.getStatus() == null ? null : order.getStatus().toString());
        orderResponse.setCustomer(order.getCustomer());
//        if (customerResponse != null){
//            orderResponse.setCustomerName(customerResponse.getCustomerName());
//            orderResponse.setCustomerAddress(customerResponse.getCustomerAddress());
//            orderResponse.setCustomerAddressName(customerResponse.getCustomerAddressName());
//        }
        // TODO 总部客户信息 --> 这个改为收货仓的送达方客户查询信息.
        if (receiveWmsSDO != null) {
            AllocateOrderGetCustomerResponse sapCustomerResponse = getCustomer(receiveWmsSDO.getSapDeliveryBPCode());
            if (sapCustomerResponse != null) {
                orderResponse.setSapCustomerName(sapCustomerResponse.getCustomerName());
                orderResponse.setSapCustomerAddress(sapCustomerResponse.getCustomerAddress());
                orderResponse.setSapCustomerAddressName(sapCustomerResponse.getCustomerAddressName());
            }
        }

        // 组织
        if (StringUtils.isNotBlank(order.getApplyOrgId())) {
            AllocateOrderGetOrganizationResponse orgResponse = InfoUtil.getOrganizationById(order.getApplyOrgId());
            orderResponse.setApplyOrgName(orgResponse.getName());
        }
        //发货仓组织
        if (shipWmsSDO != null) {
            AllocateOrderGetOrganizationResponse shipOrg = InfoUtil.getOrganizationById(shipWmsSDO.getSapSalesOrgId());
            orderResponse.setShipAreaOrgName(shipOrg.getName());
            orderResponse.setShipAreaName(shipWmsSDO.getName());
            orderResponse.setShipOrgName(shipOrg.getName());
        }
        if (receiveWmsSDO != null) {
            AllocateOrderGetOrganizationResponse receiveOrg = InfoUtil.getOrganizationById(receiveWmsSDO.getSapSalesOrgId());
            orderResponse.setReceiveAreaOrgName(receiveOrg.getName());
            orderResponse.setReceiveAreaName(receiveWmsSDO.getName());
            orderResponse.setReceiveOrgName(receiveOrg.getName());
        }
        orderResponse.setProductGroup(order.getProductGroup());
        orderResponse.setProductGroupDesc("常温");
        orderResponse.setReturnOrder(order.getReturnOrder());
        orderResponse.setReturnOrderDesc(Objects.equals(Boolean.TRUE, order.getReturnOrder()) ?
                "是" : "否");
        orderResponse.setApplyOrgId(order.getApplyOrgId());
        orderResponse.setShipAreaId(order.getShipAreaId());
        orderResponse.setShipWarehouseId(order.getShipWarehouseId());
        orderResponse.setReceiveAreaId(order.getReceiveAreaId());
        orderResponse.setReceiveWarehouseId(order.getReceiveWarehouseId());
        orderResponse.setShipMethod(order.getShipMethod() == null ? null : String.valueOf(order.getShipMethod()));
        orderResponse.setExpectedDeliveryDate(TimeUtil.formatYYYY_MM_dd(order.getExpectedDeliveryDate()));
        orderResponse.setExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(order.getExpectedDeliveryDate()));
        orderResponse.setDocDate(TimeUtil.formatYYYY_MM_dd(order.getDocDate()));
        orderResponse.setDocDateStr(TimeUtil.formatYYYY_MM_dd(order.getDocDate()));
        orderResponse.setSapRefPoNo(order.getSapRefPoNo());
        orderResponse.setSapCostCenter(order.getSapCostCenter());
        orderResponse.setSapSalesOrgId(order.getSapSalesOrgId());
        orderResponse.setSapChannel(order.getSapChannel());

        orderResponse.setCreator(NameUtil.getRealName(order.getCreator()));
        orderResponse.setModifier(NameUtil.getRealName(order.getUpdater()));
        orderResponse.setCreateTime(order.getGmt_create());
        orderResponse.setUpdateTime(order.getGmt_modified());
        orderResponse.setOrderReasonDesc(getOrderReason(order.getOrderReason()));

        orderResponse.setOrderReason(order.getOrderReason());
        orderResponse.setSapInternalSalesBPCode(receiveWmsSDO.getSapInternalSalesBPCode());
        orderResponse.setSapInternalDeliveryBPCode(receiveWmsSDO.getSapInternalDeliveryBPCode());
        orderResponse.setSapDeliveryBPCode(receiveWmsSDO.getSapDeliveryBPCode());
        orderResponse.setSapSalesBPCode(receiveWmsSDO.getSapSalesBPCode());
        orderResponse.setRemark(order.getRemark());

        return orderResponse;
    }

    private boolean isDateError(String date) {
        if (StringUtils.isNotEmpty(date)) {
            Date dateOld = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String sameDayDateString = dateFormat.format(new Date());
            Date sameDayDate = null;
            try {
                sameDayDate = dateFormat.parse(sameDayDateString);
                dateOld = dateFormat.parse(date);
            } catch (ParseException e) {
                return false;
            }

            if (dateOld.getTime() >= sameDayDate.getTime()) {
                return true;
            }
        }
        return false;
    }

    @Data
    class WarehouseBaseInfo {
        private String receiveWarehouseId;
        private String receiveWarehouseName;
        private String deliveryWarehouseId;
        private String deliveryWarehouseName;
        private String sapDeliveryBPCode;
        private String sapSalesBPCode;
        private String sapInternalDeliveryBPCode;
        private String sapInternalSalesBPCode;
    }

    private WarehouseBaseInfo checkWarehouse(String receiveWarehouseCode, String deliveryWarehouseCode, Integer type, Integer isDTC) {
        WarehouseBaseInfo warehouseBaseInfo = new WarehouseBaseInfo();

        DeliveryWarehouseChoiceDTO receiveWarehouse = new DeliveryWarehouseChoiceDTO();
        DeliveryWarehouseChoiceDTO deliveryWarehouse = new DeliveryWarehouseChoiceDTO();
        //不是直发客户单子，需要查找收货仓，接口带权限校验
        if (!new Integer(1).equals(isDTC)&&StringUtils.isNotEmpty(receiveWarehouseCode)) {
            QueryReceivingWarehouseByTypeRequest queryReceivingWarehouseByTypeRequest = new QueryReceivingWarehouseByTypeRequest();
            queryReceivingWarehouseByTypeRequest.setCode(receiveWarehouseCode);
            queryReceivingWarehouseByTypeRequest.setType(type.toString());
            Result<List<DeliveryWarehouseChoiceDTO>> receiveWarehouseRes = forecastWarehouseService.queryReceivingWarehouseByType(queryReceivingWarehouseByTypeRequest);
            //收货仓实体
            if (Objects.nonNull(receiveWarehouseRes)&& org.apache.commons.collections.CollectionUtils.isNotEmpty(receiveWarehouseRes.getResult())) {
                receiveWarehouse = receiveWarehouseRes.getResult().get(0);
            }
        }
        //查找发货仓库，接口带权限校验
        if (StringUtils.isNotEmpty(deliveryWarehouseCode)) {
            QueryDeliveryWarehouseByTypeRequest batchDeliveryWarehouseByIdsRequest = new QueryDeliveryWarehouseByTypeRequest();
            batchDeliveryWarehouseByIdsRequest.setCode(deliveryWarehouseCode);
            batchDeliveryWarehouseByIdsRequest.setType(type.toString());
            Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouseRes = forecastWarehouseService.queryDeliveryWarehouseByType(batchDeliveryWarehouseByIdsRequest);
            if (Objects.nonNull(deliveryWarehouseRes)&& org.apache.commons.collections.CollectionUtils.isNotEmpty(deliveryWarehouseRes.getResult())) {
                deliveryWarehouse = deliveryWarehouseRes.getResult().get(0);
            }
        }
        //获取对应收发所需要的值
        warehouseBaseInfo.setDeliveryWarehouseId(deliveryWarehouse.getValue());
        if (!new Integer(1).equals(isDTC)) {
            warehouseBaseInfo.setReceiveWarehouseId(receiveWarehouse.getValue());
        }
        warehouseBaseInfo.setSapDeliveryBPCode(deliveryWarehouse.getSapDeliveryBPCode());
        warehouseBaseInfo.setSapSalesBPCode(deliveryWarehouse.getSapSaleBPCode());
        warehouseBaseInfo.setSapInternalDeliveryBPCode(deliveryWarehouse.getSapInternalDeliveryBPCode());
        warehouseBaseInfo.setSapInternalSalesBPCode(deliveryWarehouse.getSapInternalSalesBPCode());
        return warehouseBaseInfo;
    }

    /**
     * 保存草稿
     *
     * @param request
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String save(AllocateOrderSaveRequest request) {
        AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
        loadListRequest.setCode(request.getCode());
        Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(loadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-060");
        }
        AllocateOrder allocateOrder = result.getResult().get(0);
        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(request.getExpectedDeliveryTime()));
//        allocateOrder.setDocDate(TimeUtil.parseSimpleDateFormat(request.getDocDate()));
        allocateOrder.setShipMethod(request.getShipMethod() == null ? null : Integer.parseInt(request.getShipMethod()));
        allocateOrder.setSapCostCenter(request.getSapCostCenter());
        allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
        allocateOrder.setSapChannel(request.getSapChannel());
        allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
        allocateOrder.setStatus(AllocateOrderStatus.DRAFT.getValue());
        allocateOrder.setGmt_modified(new Date());
        allocateOrder.setDocDate(Optional.ofNullable(TimeUtil.parseSimpleDateFormat(request.getDocDate())).orElse(InfoUtil.docDate()));
        if (StringUtils.isNotBlank(request.getShipAreaId())) {
            WmsSDO wmsSDO = getWmsSDO(request.getShipAreaId());
            if (wmsSDO != null) {
                allocateOrder.setShipAreaId(request.getShipAreaId());
                allocateOrder.setShipWarehouseId(wmsSDO.getWarehouseId());
                allocateOrder.setShipOrgId(wmsSDO.getSapSalesOrgId());
            }
        }
        UpdateAllocateOrderResponse updateAllocateOrderResponse = allocateOrderService.updateAllocateOrder(allocateOrder);
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
//            boolean match = request.getAllocateOrderScItemDetails().stream()
//                    .anyMatch(x -> StringUtils.isBlank(x.getProductDate()));
//            if (match){
//                throw new FacadeException("OTS-03-005-00-15-050");
//            }
            DeletesRequest deletesRequest = new DeletesRequest();
            deletesRequest.setCode(request.getCode());
            allocateOrderDetailService.deletes(deletesRequest);
            int i = 1;
            for (AllocateOrderScItemDetail detail : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
                allocateOrderDetail.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
                allocateOrderDetail.setAllocateOrderId(allocateOrder.getId());
                allocateOrderDetail.setLineNo(StringUtils.isBlank(detail.getLineNo()) ? i : Integer.parseInt(detail.getLineNo()));
                allocateOrderDetail.setAllocateOrderCode(allocateOrder.getCode());
                allocateOrderDetail.setQuantity(StringUtils.isBlank(detail.getApplyQuantity()) ? null : detail.getApplyQuantity().trim());
                if (StringUtils.isNotBlank(detail.getGoodsId())) {
                    allocateOrderDetail.setScItemId(detail.getGoodsId());
                } else if (StringUtils.isNotBlank(detail.getId())) {
                    allocateOrderDetail.setScItemId(detail.getId());
                } else {
                    throw new FacadeException("OTS-03-005-00-15-033");
                }
                allocateOrderDetail.setScItemCode(detail.getScItemId());
                allocateOrderDetail.setClose(false);
                allocateOrderDetail.setUnit(StringUtils.isNotBlank(detail.getUnit()) ? detail.getUnit() :
                        InfoUtil.getUnit(detail.getGoodsId()));
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ? null : detail.getConfirmedQuantity().trim());

                allocateOrderDetail.setProductGroup("11");
                allocateOrderDetail.setReturnOrder(false);
                allocateOrderDetail.setRemarks(detail.getRemark());
                allocateOrderDetail.setStatus(AllocateOrderStatus.DRAFT.getValue());
                //TODO 价格可能需要再查询一遍
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getPrice())?null:detail.getPrice().trim());
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getUnitPrice())?null:detail.getUnitPrice());
                allocateOrderDetail.setPrice(detail.getUnitPrice() == null ? null : detail.getUnitPrice().toString());
                if (StringUtils.isNotBlank(detail.getProductDate())) {
                    allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(detail.getProductDate()));
                }
                if (StringUtils.isNotBlank(detail.getExpectedDeliveryDate())) {
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(detail.getExpectedDeliveryDate()));
                } else {
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(request.getExpectedDeliveryDate()));
                }
                allocateOrderDetail.setIsDTC(false);
                allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
                i++;
            }
        }
        return allocateOrder.getCode();
    }

    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String saveUpdate(AllocateOrderSaveRequest request) {
        AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
        loadListRequest.setCode(request.getCode());
        Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(loadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-060");
        }
        AllocateOrder allocateOrder = result.getResult().get(0);
        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(request.getExpectedDeliveryTime()));
//        allocateOrder.setDocDate(TimeUtil.parseSimpleDateFormat(request.getDocDate()));
        allocateOrder.setShipMethod(request.getShipMethod() == null ? null : Integer.parseInt(request.getShipMethod()));
        allocateOrder.setSapCostCenter(request.getSapCostCenter());
        allocateOrder.setSapRefPoNo(request.getSapRefPoNo());
        allocateOrder.setSapChannel(request.getSapChannel());
        allocateOrder.setSapSalesOrgId(request.getSapSalesOrgId());
//        allocateOrder.setStatus(AllocateOrderStatus.DRAFT.getValue());
        allocateOrder.setGmt_modified(new Date());
        allocateOrder.setRemark(request.getRemark());
        allocateOrder.setShipWarehouseId(request.getShipWareHouseId());
        allocateOrder.setReceiveWarehouseId(request.getReceiveWareHouseId());
        allocateOrder.setDocDate(Optional.ofNullable(TimeUtil.parseSimpleDateFormat(request.getDocDate())).orElse(InfoUtil.docDate()));
//        if (StringUtils.isNotBlank(request.getShipAreaId())) {
//            WmsSDO wmsSDO = getWmsSDO(request.getShipAreaId());
//            if (wmsSDO != null) {
//                allocateOrder.setShipAreaId(request.getShipAreaId());
//                allocateOrder.setShipWarehouseId(wmsSDO.getWarehouseId());
//                allocateOrder.setShipOrgId(wmsSDO.getSapSalesOrgId());
//            }
//        }
        allocateOrder.setFeatures(request.getFeatures());
        UpdateAllocateOrderResponse updateAllocateOrderResponse = allocateOrderService.updateAllocateOrder(allocateOrder);
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
//            boolean match = request.getAllocateOrderScItemDetails().stream()
//                    .anyMatch(x -> StringUtils.isBlank(x.getProductDate()));
//            if (match){
//                throw new FacadeException("OTS-03-005-00-15-050");
//            }
            // 修改前详情数据
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
            Result<List<AllocateOrderDetail>> allocateOrderDetailResult = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            Map<String, AllocateOrderDetail> allocateOrderDetailOldMap = new HashMap<>();
            if(allocateOrderDetailResult.getResult() != null){
                List<AllocateOrderDetail> allocateOrderDetailList = allocateOrderDetailResult.getResult();
                allocateOrderDetailOldMap = allocateOrderDetailList.stream()
                        .collect(Collectors.toMap(AllocateOrderDetail::getScItemCode, Function.identity(), (x1, x2) -> x1));
            }

            DeletesRequest deletesRequest = new DeletesRequest();
            deletesRequest.setCode(request.getCode());
            allocateOrderDetailService.deletes(deletesRequest);
            int i = 1;
            for (AllocateOrderScItemDetail detail : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail allocateOrderDetailOld = allocateOrderDetailOldMap.get(detail.getScItemCode());
                AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
                allocateOrderDetail.setType(allocateOrder.getType());
                allocateOrderDetail.setStatus(AllocateOrderStatus.DRAFT.getValue());
                allocateOrderDetail.setOutAllocateOrderLineId(detail.getOuterLineNo());
                allocateOrderDetail.setAllocateOrderId(allocateOrder.getId());
                allocateOrderDetail.setLineNo(StringUtils.isBlank(detail.getLineNo()) ? i : Integer.parseInt(detail.getLineNo()));
                allocateOrderDetail.setAllocateOrderCode(allocateOrder.getCode());
                allocateOrderDetail.setQuantity(StringUtils.isBlank(detail.getQuantity()) ? null : detail.getQuantity().trim());
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ? detail.getQuantity() : detail.getConfirmedQuantity().trim());
//                if (StringUtils.isNotBlank(detail.getGoodsId())) {
//                    allocateOrderDetail.setScItemId(detail.getGoodsId());
//                } else if (StringUtils.isNotBlank(detail.getId())) {
//                    allocateOrderDetail.setScItemId(detail.getId());
//                } else {
//                    throw new FacadeException("OTS-03-005-00-15-033");
//                }
                allocateOrderDetail.setScItemId(detail.getScItemId());
                allocateOrderDetail.setScItemCode(detail.getScItemCode());
                allocateOrderDetail.setScItemName(detail.getScItemName());
                allocateOrderDetail.setClose(false);
                allocateOrderDetail.setUnit(StringUtils.isNotBlank(detail.getUnit()) ? detail.getUnit() :
                        InfoUtil.getUnit(detail.getGoodsId()));
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ? null : detail.getConfirmedQuantity().trim());

//                allocateOrderDetail.setProductGroup("11");
                allocateOrderDetail.setReturnOrder(allocateOrder.getReturnOrder());
                allocateOrderDetail.setRemarks(detail.getRemark());
//                allocateOrderDetail.setStatus(AllocateOrderStatus.DRAFT.getValue());
                //TODO 价格可能需要再查询一遍
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getPrice())?null:detail.getPrice().trim());
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getUnitPrice())?null:detail.getUnitPrice());
                allocateOrderDetail.setPrice(detail.getUnitPrice() == null ? null : detail.getUnitPrice().toString());
                if (StringUtils.isNotBlank(detail.getProductDate())) {
                    allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(detail.getProductDate()));
                }else if(allocateOrderDetailOld != null){
                    allocateOrderDetail.setExpectedProduceDate(allocateOrderDetailOld.getExpectedProduceDate());
                }
                if (StringUtils.isNotBlank(detail.getExpectedDeliveryDate())) {
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(detail.getExpectedDeliveryDate()));
                } else {
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(request.getExpectedDeliveryDate()));
                }
                allocateOrderDetail.setIsDTC(false);
                allocateOrderDetail.setThirdLineNo(detail.getThirdLineNo());
                allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
                i++;
            }
        }
        return allocateOrder.getCode();
    }

    @Override
    public AllocateOrderCreateResponse updateAllocateOrder(AllocateOrderSaveRequest request) {
        AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
        loadListRequest.setCode(request.getCode());
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("loadAllocateOrderList");
        Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(loadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-060", "没有找到对应的调拨单");
        }
        stopWatch.stop();
        AllocateOrder allocateOrder = result.getResult().get(0);
        allocateOrder.setUpdater(request.getOperatorId());
        allocateOrder.setOperatorId(request.getOperatorId());
        if (Boolean.TRUE.equals(request.getSubmitFlag()) && AllocateOrderStatus.DRAFT.getValue().equals(allocateOrder.getStatus())) {
            allocateOrder.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
        }
        // 如果request中的发货仓编码，不为空，就更新到调拨单上
        if (StringUtils.isNotBlank(request.getShipWareHouseId())) {
            allocateOrder.setShipWarehouseId(request.getShipWareHouseId());
        }
        if (StringUtils.isNotBlank(request.getShipAreaId())) {
            allocateOrder.setShipAreaId(request.getShipAreaId());
        }

        // 收货仓编码不为空，就更新到调拨单上
        if (StringUtils.isNotBlank(request.getReceiveWareHouseId())) {
            allocateOrder.setReceiveWarehouseId(request.getReceiveWareHouseId());
        }
        if (StringUtils.isNotBlank(request.getReceiveAreaId())) {
            allocateOrder.setReceiveAreaId(request.getReceiveAreaId());
        }

        if (StringUtils.isNotBlank(request.getTransferWarehouseId())) {
            allocateOrder.setTransferWarehouseId(request.getTransferWarehouseId());
        }


        // 是否自动创建履约单不为空，就更新到调拨单中
        if (request.getAutoFulfillment() != null) {
            allocateOrder.setAutoFulfillment(request.getAutoFulfillment());
        }
        // 履约方式不为空，就更新到调拨单中
        if (StringUtils.isNotEmpty(request.getFulfillmentTypeCode())) {
            allocateOrder.setFulfillmentTypeCode(request.getFulfillmentTypeCode());
        }

        // 订单标签不为空集合，就更新到调拨单中
        if (CollectionUtils.isNotEmpty(request.getOrderTag())) {
            allocateOrder.setOrderTag(StringUtils.join(request.getOrderTag().toArray(),","));
        }

        // 优先级不为空字符串，就更新到调拨单中
        if (StringUtils.isNotBlank(request.getPriority())) {
            allocateOrder.setPriority("100".equals(request.getPriority()) ? 100 : 1);
        }

        // 生效日期不为空，就更新到调拨单中
        if (StringUtils.isNotBlank(request.getTakeEffectDate())) {
            allocateOrder.setBeginDate(TimeUtil.parseYYYY_MM_dd(request.getTakeEffectDate()));
        }

        // 单据日期
        if (StringUtils.isNotEmpty(request.getDocDate())) {
            allocateOrder.setDocDate(TimeUtil.parseYYYY_MM_dd(request.getDocDate()));
        }

        // 期望交货日期，
        if (StringUtils.isNotEmpty(request.getExpectedDeliveryTime())) {
            allocateOrder.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(request.getExpectedDeliveryTime()));
        }
        // 运输方式
        if (StringUtils.isNotEmpty(request.getShipMethod())) {
            allocateOrder.setShipMethod(Integer.parseInt(request.getShipMethod()));
        }
        // 备注
        if (StringUtils.isNotEmpty(request.getRemark())) {
            allocateOrder.setRemark(request.getRemark());
        }

        allocateOrder.setFeatures(request.getFeatures());

        Map<String, String> bizFeatureMap = FeatureUtil.fromString(allocateOrder.getBizFeatures());
        if (MapUtils.isNotEmpty(request.getBizFeatures())) {
            bizFeatureMap.putAll(request.getBizFeatures());
        }
        allocateOrder.setBizFeatures(FeatureUtil.toString(bizFeatureMap));

        // 更新主单
        stopWatch.start("updateAllocateOrder");
        allocateOrderService.updateAllocateOrder(allocateOrder);
        stopWatch.stop();
        List<AllocateOrderDetailSDO> detailResult = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())) {
            stopWatch.start("deleteDetail");
            DeletesRequest deletesRequest = new DeletesRequest();
            deletesRequest.setCode(request.getCode());
            allocateOrderDetailService.deletes(deletesRequest);
            stopWatch.stop();
            List<String> lineNoList = request.getAllocateOrderScItemDetails().stream().map(AllocateOrderScItemDetail::getLineNo)
                    .filter(Objects::nonNull).distinct().collect(Collectors.toList());
            int i = 1;
            stopWatch.start("insertDetail");
            for (AllocateOrderScItemDetail detail : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
                allocateOrderDetail.setType(allocateOrder.getType());
                //如果是提交的 ,子单也需要改成待推送
                if (Boolean.TRUE.equals(request.getSubmitFlag())) {
                    allocateOrderDetail.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
                }else {
                    allocateOrderDetail.setStatus(AllocateOrderStatus.DRAFT.getValue());
                }
                allocateOrderDetail.setAllocateOrderId(allocateOrder.getId());
                Integer lineNo = getLineNo(i, detail.getLineNo(), lineNoList);
                allocateOrderDetail.setLineNo(lineNo);
                allocateOrderDetail.setAllocateOrderCode(allocateOrder.getCode());
                allocateOrderDetail.setClose(false);

                allocateOrderDetail.setThirdLineNo(detail.getThirdLineNo());
                allocateOrderDetail.setAllocateApplyOrderLineId(detail.getAllocateApplyOrderLineNo());
                allocateOrderDetail.setRelatedAllocateSubOrderId(detail.getRelatedAllocateSubOrderId());
                allocateOrderDetail.setScItemId(detail.getScItemId());
                allocateOrderDetail.setScItemCode(detail.getScItemCode());
                allocateOrderDetail.setScItemName(detail.getScItemName());
                allocateOrderDetail.setQuantity(StringUtils.isBlank(detail.getQuantity()) ? null : detail.getQuantity().trim());
                allocateOrderDetail.setUnit(StringUtils.isNotBlank(detail.getUnit()) ? detail.getUnit() : InfoUtil.getUnit(detail.getGoodsId()));
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ? null : detail.getConfirmedQuantity().trim());
                allocateOrderDetail.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
                allocateOrderDetail.setReturnOrder(allocateOrder.getReturnOrder());
                allocateOrderDetail.setRemarks(detail.getRemark());
                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(detail.getProductDate()));
                allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(request.getExpectedDeliveryDate()));
                allocateOrderDetail.setCreator(detail.getCreator());
                allocateOrderDetail.setUpdater(allocateOrder.getUpdater());
                allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);

                // 返回结果
                AllocateOrderDetailSDO detailSDO = new AllocateOrderDetailSDO();
                detailSDO.setLineNo(lineNo.toString());
                detailSDO.setThirdLineNo(allocateOrderDetail.getThirdLineNo());
                detailResult.add(detailSDO);
            }
            stopWatch.stop();
        }
        log.info("AllocateOrderWriteRepository|updateAllocateOrder|cost={}",stopWatch.prettyPrint());
        AllocateOrderCreateResponse response = new AllocateOrderCreateResponse();
        response.setCode(request.getCode());
        response.setAllocateOrderDetailList(detailResult);
        return response;
    }

    private Integer getLineNo(Integer i, String lineNo, List<String> lineNoList) {
        if (StringUtils.isNotBlank(lineNo)) {
            return Integer.parseInt(lineNo);
        }

        while (lineNoList.contains(i.toString())) {
            i++;
        }

        return i;
    }

    //非总部销售调拨单处于待推送状状态, 重新推送
    public String notSaleOrderSubmit(AllocateOrderSubmitRequest request,AllocateOrder allocateOrder){
        if (CollectionUtils.isNotEmpty(request.getAllocateOrderScItemDetails())){

            boolean match = request.getAllocateOrderScItemDetails().stream()
                    .anyMatch(x -> StringUtils.isBlank(x.getProductDate()));
            if (match) {
                throw new FacadeException("OTS-03-005-00-15-050");
            }
            DeletesRequest deletesRequest = new DeletesRequest();
            deletesRequest.setCode(allocateOrder.getCode());
            allocateOrderDetailService.deletes(deletesRequest);
            AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
            if (StringUtils.isNotBlank(allocateOrder.getAllocateApplyOrderId())){
                LoadAllocateApplyOrderRequest loadAllocateApplyOrderRequest = new LoadAllocateApplyOrderRequest();
                loadAllocateApplyOrderRequest.setId(allocateOrder.getAllocateApplyOrderId());
                allocateApplyOrder = allocateApplyOrderService.loadAllocateApplyOrder(loadAllocateApplyOrderRequest);
            }

            int i = 1;
            for (AllocateOrderScItemDetail detail : request.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
                allocateOrderDetail.setAllocateOrderCode(allocateOrder.getCode());
                allocateOrderDetail.setLineNo(StringUtils.isBlank(detail.getLineNo()) ? i : Integer.parseInt(detail.getLineNo()));
                String quantity = null;
                if (StringUtils.isNotBlank(detail.getApplyQuantity())) {
                    quantity = detail.getApplyQuantity().trim();
                } else if (StringUtils.isNotBlank(detail.getQuantity())) {
                    quantity = detail.getQuantity().trim();
                }
                allocateOrderDetail.setQuantity(quantity);
                if (StringUtils.isNotBlank(detail.getGoodsId())) {
                    allocateOrderDetail.setScItemId(detail.getGoodsId());
                } else if (StringUtils.isNotBlank(detail.getId())) {
                    allocateOrderDetail.setScItemId(detail.getId());
                } else {
                    throw new FacadeException("OTS-03-005-00-15-075");
                }
                AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest = new AllocateApplyOrderDetailLoadListRequest();
                if (allocateApplyOrder.getId() != null){
                    allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrder.getId().intValue());
                    allocateApplyOrderDetailLoadListRequest.setGoodsId(allocateOrderDetail.getScItemId());
                    Result<List<AllocateApplyOrderDetail>> listResult = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
                    if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                        AllocateApplyOrderDetail allocateApplyOrderDetail = listResult.getResult().get(0);
                        allocateOrderDetail.setSendBackRequired("1".equals(allocateApplyOrderDetail.getSendBackRequired())?true:false);
                        allocateOrderDetail.setOutAllocateApplyOrderLineId(allocateApplyOrderDetail.getOutLineNo());
                        allocateOrderDetail.setAllocateApplyOrderLineId(allocateApplyOrderDetail.getLineNo()==null?null:allocateApplyOrderDetail.getLineNo().toString());
                        allocateOrderDetail.setSubTotalAmount(allocateApplyOrderDetail.getSubtotalMoney() == null ?null
                                :allocateApplyOrderDetail.getSubtotalMoney().toString());
                        allocateOrderDetail.setDiscountAmount(allocateApplyOrderDetail.getSubtotalMoney() == null? null
                                :allocateApplyOrderDetail.getSubtotalMoney().toString());
                        allocateOrderDetail.setExchangeAmt(allocateApplyOrderDetail.getExchangeAmt() == null? null
                                :allocateApplyOrderDetail.getExchangeAmt().toString());
                    }

                }

                allocateOrderDetail.setScItemCode(detail.getScItemId());
                if (StringUtils.isNotBlank(detail.getExpectedDeliveryDate())) {
//                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(detail.getExpectedDeliveryDate()));
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(detail.getExpectedDeliveryDate()));
                } else {
                    allocateOrderDetail.setExpectedDeliveryDate(allocateOrder.getExpectedDeliveryDate());
                }
                allocateOrderDetail.setRemarks(detail.getRemark());
                allocateOrderDetail.setAllocateOrderId(allocateOrder.getId());
                allocateOrderDetail.setScItemCode(detail.getScItemId());
                allocateOrderDetail.setScItemName(detail.getScItemName());
                allocateOrderDetail.setType(allocateOrder.getType());
//                allocateOrderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());

                allocateOrderDetail.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
                allocateOrderDetail.setClose(false);

                allocateOrderDetail.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
                allocateOrderDetail.setApplyQuantity(InfoUtil.getLong(detail.getApplyQuantity()));
//                allocateOrderDetail.setApplyQuantity(StringUtils.isBlank(detail.getApplyQuantity()) ? null : Long.parseLong(detail.getApplyQuantity().trim()));
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ?
                        null : detail.getConfirmedQuantity().trim());
                String unit = InfoUtil.getUnit(detail.getGoodsId());
                if (!StringUtils.equals(unit, detail.getUnit())) {
                    allocateOrderDetail.setUnit(detail.getUnit());
                } else {
                    allocateOrderDetail.setUnit(unit);
                }

                allocateOrderDetail.setReturnOrder(allocateOrder.getReturnOrder() == null ? false : allocateOrder.getReturnOrder());
//                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseSimpleDateFormat(detail.getProductDate()));
                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(detail.getProductDate()));

                //TODO 价格问题
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getPrice())?null:detail.getPrice().trim());
                allocateOrderDetail.setPrice(detail.getUnitPrice() == null ? null : detail.getUnitPrice().toString());
                allocateOrderDetail.setIsDTC(false);
                allocateOrderDetail.setThirdLineNo(detail.getThirdLineNo());
                allocateOrderDetail.setAllocateApplyOrderLineId(detail.getAllocateApplyOrderLineNo());
                allocateOrderDetail.setRelatedAllocateSubOrderId(detail.getRelatedAllocateSubOrderId());
                allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
                i++;
            }
        }
        return allocateOrder.getCode();
    }
    /**
     * 提交调拨单 F1-B -- 也包含退单
     *
     * @param allocateOrderSubmitRequest
     * @return
     */
    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public String submit(AllocateOrderSubmitRequest allocateOrderSubmitRequest) {
        AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
        loadListRequest.setCode(allocateOrderSubmitRequest.getCode());
        Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(loadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-061");
        }
        // 提交的时候不允许 货品为空
        if (CollectionUtils.isEmpty(allocateOrderSubmitRequest.getAllocateOrderScItemDetails())) {
            throw new FacadeException("OTS-03-005-00-15-059");
        }
        AllocateOrder allocateOrder = result.getResult().get(0);


        //可编辑字段
        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(allocateOrderSubmitRequest.getExpectedDeliveryDate()));
//        allocateOrder.setDocDate(TimeUtil.parseSimpleDateFormat(allocateOrderSubmitRequest.getDocDate()));
        allocateOrder.setShipMethod(allocateOrderSubmitRequest.getShipMethod() == null ? null : Integer.parseInt(allocateOrderSubmitRequest.getShipMethod()));
        allocateOrder.setSapCostCenter(allocateOrderSubmitRequest.getSapCostCenter());
        allocateOrder.setSapRefPoNo(allocateOrderSubmitRequest.getSapRefPoNo());
        allocateOrder.setSapChannel(allocateOrderSubmitRequest.getSapChannel());
        allocateOrder.setSapSalesOrgId(allocateOrderSubmitRequest.getSapSalesOrgId());

//        allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
        allocateOrder.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
        allocateOrder.setGmt_modified(new Date());
        allocateOrder.setDocDate(Optional.ofNullable(TimeUtil.parseYYYY_MM_dd(allocateOrderSubmitRequest.getDocDate()))
                .orElse(InfoUtil.salesDocDate()));
//        allocateOrder.setDocDate(Optional.ofNullable(TimeUtil.parseSimpleDateFormat(allocateOrderSubmitRequest.getDocDate()))
//                .orElse(InfoUtil.salesDocDate()));
        allocateOrder.setSubmitTime(new Date());
        if (StringUtils.isNotBlank(allocateOrderSubmitRequest.getShipAreaId())) {
            WmsSDO wmsSDO = getWmsSDO(allocateOrderSubmitRequest.getShipAreaId());
            if (wmsSDO != null) {
                allocateOrder.setShipAreaId(allocateOrderSubmitRequest.getShipAreaId());
                allocateOrder.setShipWarehouseId(wmsSDO.getWarehouseId());
                allocateOrder.setShipOrgId(wmsSDO.getSapSalesOrgId());
            }
        }
        UpdateAllocateOrderResponse updateAllocateOrderResponse = allocateOrderService.updateAllocateOrder(allocateOrder);
        //增加一段非总部销售的重新推送处理逻辑
        if (!Objects.equals(allocateOrder.getType(), AllocateOrderTypeEnum.HEADQUARTER_SALES.getType())){
            return notSaleOrderSubmit(allocateOrderSubmitRequest,allocateOrder);
        }
        if (CollectionUtils.isNotEmpty(allocateOrderSubmitRequest.getAllocateOrderScItemDetails())) {

            boolean match = allocateOrderSubmitRequest.getAllocateOrderScItemDetails().stream()
                    .anyMatch(x -> StringUtils.isBlank(x.getProductDate()));
            if (match) {
                throw new FacadeException("OTS-03-005-00-15-050");
            }
            DeletesRequest deletesRequest = new DeletesRequest();
            deletesRequest.setCode(allocateOrder.getCode());
            allocateOrderDetailService.deletes(deletesRequest);
            int i = 1;
            for (AllocateOrderScItemDetail detail : allocateOrderSubmitRequest.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
                allocateOrderDetail.setAllocateOrderCode(allocateOrder.getCode());
                allocateOrderDetail.setLineNo(StringUtils.isBlank(detail.getLineNo()) ? i : Integer.parseInt(detail.getLineNo()));
                String quantity = null;
                if (StringUtils.isNotBlank(detail.getApplyQuantity())) {
                    quantity = detail.getApplyQuantity().trim();
                } else if (StringUtils.isNotBlank(detail.getQuantity())) {
                    quantity = detail.getQuantity().trim();
                }
                allocateOrderDetail.setQuantity(quantity);
                if (StringUtils.isNotBlank(detail.getGoodsId())) {
                    allocateOrderDetail.setScItemId(detail.getGoodsId());
                } else if (StringUtils.isNotBlank(detail.getId())) {
                    allocateOrderDetail.setScItemId(detail.getId());
                } else {
                    throw new FacadeException("OTS-03-005-00-15-075");
                }
                allocateOrderDetail.setScItemCode(detail.getScItemId());
                if (StringUtils.isNotBlank(detail.getExpectedDeliveryDate())) {
//                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(detail.getExpectedDeliveryDate()));
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(detail.getExpectedDeliveryDate()));
                } else {
                    allocateOrderDetail.setExpectedDeliveryDate(allocateOrder.getExpectedDeliveryDate());
                }
                allocateOrderDetail.setRemarks(detail.getRemark());
                allocateOrderDetail.setAllocateOrderId(allocateOrder.getId());
                allocateOrderDetail.setScItemCode(detail.getScItemId());
                allocateOrderDetail.setScItemName(detail.getScItemName());
                allocateOrderDetail.setType(allocateOrder.getType());
//                allocateOrderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());

                allocateOrderDetail.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
                allocateOrderDetail.setClose(false);

                allocateOrderDetail.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
                allocateOrderDetail.setApplyQuantity(InfoUtil.getLong(detail.getApplyQuantity()));
//                allocateOrderDetail.setApplyQuantity(StringUtils.isBlank(detail.getApplyQuantity()) ? null : Long.parseLong(detail.getApplyQuantity().trim()));
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ?
                        null : detail.getConfirmedQuantity().trim());
                allocateOrderDetail.setUnit(InfoUtil.getUnit(detail.getGoodsId()));

                allocateOrderDetail.setReturnOrder(allocateOrder.getReturnOrder() == null ? false : allocateOrder.getReturnOrder());
//                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseSimpleDateFormat(detail.getProductDate()));
                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(detail.getProductDate()));

                //TODO 价格问题
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getPrice())?null:detail.getPrice().trim());
                allocateOrderDetail.setPrice(detail.getUnitPrice() == null ? null : detail.getUnitPrice().toString());
                allocateOrderDetail.setIsDTC(false);
                allocateOrderDetail.setThirdLineNo(detail.getThirdLineNo());
                allocateOrderDetail.setAllocateApplyOrderLineId(detail.getAllocateApplyOrderLineNo());
                allocateOrderDetail.setRelatedAllocateSubOrderId(detail.getRelatedAllocateSubOrderId());
                allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
                i++;
            }
        }
        return allocateOrder.getCode();
    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public String submitNotCheck(AllocateOrderSubmitRequest allocateOrderSubmitRequest) {
        AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
        loadListRequest.setCode(allocateOrderSubmitRequest.getCode());
        Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(loadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-061");
        }
        // 提交的时候不允许 货品为空
        if (CollectionUtils.isEmpty(allocateOrderSubmitRequest.getAllocateOrderScItemDetails())) {
            throw new FacadeException("OTS-03-005-00-15-059");
        }
        AllocateOrder allocateOrder = result.getResult().get(0);


        //可编辑字段
        allocateOrder.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(allocateOrderSubmitRequest.getExpectedDeliveryDate()));
//        allocateOrder.setDocDate(TimeUtil.parseSimpleDateFormat(allocateOrderSubmitRequest.getDocDate()));
        allocateOrder.setShipMethod(allocateOrderSubmitRequest.getShipMethod() == null ? null : Integer.parseInt(allocateOrderSubmitRequest.getShipMethod()));
        allocateOrder.setSapCostCenter(allocateOrderSubmitRequest.getSapCostCenter());
        allocateOrder.setSapRefPoNo(allocateOrderSubmitRequest.getSapRefPoNo());
        allocateOrder.setSapChannel(allocateOrderSubmitRequest.getSapChannel());
        allocateOrder.setSapSalesOrgId(allocateOrderSubmitRequest.getSapSalesOrgId());

//        allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
        allocateOrder.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
        allocateOrder.setGmt_modified(new Date());
        allocateOrder.setUpdater(allocateOrderSubmitRequest.getUpdater());
        allocateOrder.setDocDate(Optional.ofNullable(TimeUtil.parseYYYY_MM_dd(allocateOrderSubmitRequest.getDocDate()))
                .orElse(InfoUtil.salesDocDate()));
//        allocateOrder.setDocDate(Optional.ofNullable(TimeUtil.parseSimpleDateFormat(allocateOrderSubmitRequest.getDocDate()))
//                .orElse(InfoUtil.salesDocDate()));
        allocateOrder.setSubmitTime(new Date());
        if (StringUtils.isNotBlank(allocateOrderSubmitRequest.getShipAreaId())) {
            WmsSDO wmsSDO = getWmsSDO(allocateOrderSubmitRequest.getShipAreaId());
            if (wmsSDO != null) {
                allocateOrder.setShipAreaId(allocateOrderSubmitRequest.getShipAreaId());
                allocateOrder.setShipWarehouseId(wmsSDO.getWarehouseId());
                allocateOrder.setShipOrgId(wmsSDO.getSapSalesOrgId());
            }
        }
        UpdateAllocateOrderResponse updateAllocateOrderResponse = allocateOrderService.updateAllocateOrder(allocateOrder);
        //增加一段非总部销售的重新推送处理逻辑
        if (!Objects.equals(allocateOrder.getType(), AllocateOrderTypeEnum.HEADQUARTER_SALES.getType())){
            return notSaleOrderSubmit(allocateOrderSubmitRequest,allocateOrder);
        }
        if (CollectionUtils.isNotEmpty(allocateOrderSubmitRequest.getAllocateOrderScItemDetails())) {

            /*boolean match = allocateOrderSubmitRequest.getAllocateOrderScItemDetails().stream()
                    .anyMatch(x -> StringUtils.isBlank(x.getProductDate()));
            if (match) {
                throw new FacadeException("OTS-03-005-00-15-050");
            }*/
            DeletesRequest deletesRequest = new DeletesRequest();
            deletesRequest.setCode(allocateOrder.getCode());
            allocateOrderDetailService.deletes(deletesRequest);
            int i = 1;
            for (AllocateOrderScItemDetail detail : allocateOrderSubmitRequest.getAllocateOrderScItemDetails()) {
                AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
                allocateOrderDetail.setAllocateOrderCode(allocateOrder.getCode());
                allocateOrderDetail.setLineNo(StringUtils.isBlank(detail.getLineNo()) ? i : Integer.parseInt(detail.getLineNo()));
                allocateOrderDetail.setQuantity(StringUtils.isBlank(detail.getApplyQuantity()) ? null : detail.getApplyQuantity().trim());
                if (StringUtils.isNotBlank(detail.getGoodsId())) {
                    allocateOrderDetail.setScItemId(detail.getGoodsId());
                } else if (StringUtils.isNotBlank(detail.getId())) {
                    allocateOrderDetail.setScItemId(detail.getId());
                } else {
                    throw new FacadeException("OTS-03-005-00-15-075");
                }
                allocateOrderDetail.setScItemCode(detail.getScItemId());
                if (StringUtils.isNotBlank(detail.getExpectedDeliveryDate())) {
//                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(detail.getExpectedDeliveryDate()));
                    allocateOrderDetail.setExpectedDeliveryDate(TimeUtil.parseYYYY_MM_dd(detail.getExpectedDeliveryDate()));
                } else {
                    allocateOrderDetail.setExpectedDeliveryDate(allocateOrder.getExpectedDeliveryDate());
                }
                allocateOrderDetail.setRemarks(detail.getRemark());
                allocateOrderDetail.setAllocateOrderId(allocateOrder.getId());
                allocateOrderDetail.setScItemCode(detail.getScItemId());
                allocateOrderDetail.setScItemName(detail.getScItemName());
                allocateOrderDetail.setType(allocateOrder.getType());
//                allocateOrderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());

                allocateOrderDetail.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
                allocateOrderDetail.setClose(false);

                allocateOrderDetail.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
                allocateOrderDetail.setApplyQuantity(InfoUtil.getLong(detail.getApplyQuantity()));
//                allocateOrderDetail.setApplyQuantity(StringUtils.isBlank(detail.getApplyQuantity()) ? null : Long.parseLong(detail.getApplyQuantity().trim()));
                allocateOrderDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmedQuantity()) ?
                        null : detail.getConfirmedQuantity().trim());
                allocateOrderDetail.setUnit(InfoUtil.getUnit(detail.getGoodsId()));

                allocateOrderDetail.setReturnOrder(allocateOrder.getReturnOrder() == null ? false : allocateOrder.getReturnOrder());
//                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseSimpleDateFormat(detail.getProductDate()));
                allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(detail.getProductDate()));

                //TODO 价格问题
//                allocateOrderDetail.setPrice(StringUtils.isBlank(detail.getPrice())?null:detail.getPrice().trim());
                allocateOrderDetail.setPrice(detail.getUnitPrice() == null ? null : detail.getUnitPrice().toString());
                allocateOrderDetail.setIsDTC(false);
                allocateOrderDetail.setThirdLineNo(detail.getThirdLineNo());
                allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
                i++;
            }
        }
        return allocateOrder.getCode();
    }

    /**
     * 发货接口
     *
     * @param request
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderShippedResponse shipped(AllocateOrderShippedRequest request) {
        AllocateOrderShippedResponse response = new AllocateOrderShippedResponse();
        if (request == null || StringUtils.isBlank(request.getId())
                || CollectionUtils.isEmpty(request.getShippedScItemDTOS())) {
            throw new FacadeException("OTS-03-005-00-15-005");
        }
        if (StringUtils.isBlank(request.getOutMaterialCertificateId())) {
            throw new FacadeException("OTS-03-005-00-15-052");
        }
        List<AllocateOrderShippedScItemDTO> shipScItems = request.getShippedScItemDTOS().stream().filter(x ->
                        StringUtils.isNotBlank(x.getShipQuantity()) && StringUtils.isNotBlank(x.getScItemId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(shipScItems)) {
            throw new FacadeException("OTS-03-005-00-15-017");
        }
        //数量小于0报错
        boolean illegal = shipScItems.stream().anyMatch(x -> InfoUtil.getInt(x.getShipQuantity()) <= 0);
        if (illegal) {
            throw new FacadeException("OTS-03-005-00-15-018");
        }
        LoadAllocateOrderRequest loadAllocateOrderRequest = new LoadAllocateOrderRequest();
        loadAllocateOrderRequest.setId(request.getId());
        AllocateOrder allocateOrder = allocateOrderService.loadAllocateOrder(loadAllocateOrderRequest);
        if (allocateOrder == null) {
            throw new FacadeException("OTS-03-005-00-15-062");
        }
        //校验物料凭证号是否请求过了.
        boolean checkOut = InfoUtil.checkContain(allocateOrder.getShipOutMaterialCertificateId(),
                request.getOutMaterialCertificateId());
        if (checkOut) {
            log.error("调拨单发货请求重复:{}", JSON.toJSONString(request));
            return response;
        }

        //判断是否是电商调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(allocateOrder.getReceiveOrgId());
        //电商调拨单 聚合 scItemId - 外部行号
        //聚合相同scItemId的数量
        handleShippedScItemData(shipScItems,isECommerceOrder);
        log.info("AllocateOrderWriteRepositoryImpl.shipped.handle:{}",JSON.toJSONString(shipScItems));




        //先获取到这个调拨单的出库明细
        //出入库单的 物流信息
        //出入库单
        //看该单是否已经发货了,如果发货成功了 就直接认定发过货了.

        //计算主单的状态, 如果有全部明细全部发货 已发货, 发了 如果还有明细没有发货 -> 部分发货.
        Set<Integer> status = Sets.newHashSet();
        for (AllocateOrderShippedScItemDTO scItemDTO : shipScItems) {
            AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
            listRequest.setAllocateOrderId(Long.valueOf(request.getId()));
            listRequest.setScItemId(scItemDTO.getScItemId());
            //电商调拨单新加外部行号作为筛选条件
            if (isECommerceOrder){
                listRequest.setScItemId(null);
                listRequest.setOutAllocateOrderLineId(scItemDTO.getOutAllocateOrderLineId());
            }
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
            log.info("AllocateOrderWriteRepositoryImpl.shipped.getDetailResult,request:{},res:{}",
                    JSON.toJSONString(listRequest),JSON.toJSONString(result));
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                AllocateOrderDetail orderDetail = result.getResult().get(0);
                if (orderDetail.getShipQuantity() == null) {
                    orderDetail.setShipQuantity(0);
                }
                Integer shipQuantity = orderDetail.getShipQuantity();
                Integer add = InfoUtil.getInt(scItemDTO.getShipQuantity());
                Integer sum = shipQuantity + add;
                orderDetail.setShipQuantity(sum);
                // TODO 货品明细的状态  针对数量的计算
                Integer quantity = InfoUtil.getInt(orderDetail.getQuantity());

                //发货时特殊判断下是否已收货，如果已收货则不更新
                //2022.03.11 如果已经关闭了, 那就不更新状态
                if (!Objects.equals(orderDetail.getStatus(), AllocateOrderStatus.Received.getValue())
                    && !Objects.equals(orderDetail.getStatus(),AllocateOrderStatus.CLOSED.getValue())) {

                    if (quantity > sum) {
                        orderDetail.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                    } else {
                        orderDetail.setStatus(AllocateOrderStatus.Shipped.getValue());
                    }
                    status.add(orderDetail.getStatus());
                }
                if (StringUtils.isNotBlank(request.getPostingTime())) {
                    Date postingTime = TimeUtil.parseSimpleDateFormat(request.getPostingTime().trim());
                    orderDetail.setShipTime(postingTime);
                } else {
                    orderDetail.setShipTime(new Date());
                }
                orderDetail.setGmt_modified(new Date());
                //防止004其他接口的影响
                orderDetail.setReceiveTime(null);
                orderDetail.setReceiveQuantity(null);
                orderDetail.setDeliveryQuantity(null);
                orderDetail.setDeliveryDate(null);
                log.info("AllocateOrderWriteRepositoryImpl.shipped.updateAllocateOrderDetail,{}",JSON.toJSONString(orderDetail));
                allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
            }else {
                throw new FacadeException("OTS-03-005-00-15-106");
            }
        }
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        //子单有过状态更新 且库里也有数据
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
            if (CollectionUtils.isNotEmpty(status)) {
                //如果单据状态是已收货状态不做状态更新
                if (!Objects.equals(allocateOrder.getStatus(), AllocateOrderStatus.Received.getValue()) &&
                    !Objects.equals(allocateOrder.getStatus(),AllocateOrderStatus.CLOSED.getValue())) {
                    /**
                     * 1.1、如果行状态全部是已发货、主单状态变为已发货状态
                     * 1.2、行状态如果全部是已收货状态，主单状态改为已收货状态
                     * 2、行状态有一个已收货或者部分收货状态，主单就是部分收货状态
                     *
                     */
//                    boolean allDone = result.getResult().stream().filter(x-> !(Objects.equals(x.getClose(),Boolean.TRUE))).allMatch(y-> AllocateOrderStatus.Shipped.getValue().equals(y.getStatus()));
                    //是否已发货
                    boolean isShipped = true;
                    //是否已收货
                    boolean isReceived = true;
                    //是否部分收货
                    boolean isPartReceived = false;
                    //是否已关闭状态
                    boolean isClosed = true;
                    //是否代发货状态
                    boolean isShipmentProcessing = true;
                    List<AllocateOrderDetail> allocateOrderDetails = new ArrayList<>();
                    List<AllocateOrderDetail> allocateOrderDetailsClosed = new ArrayList<>();
                    for (AllocateOrderDetail allocateOrderDetail : result.getResult()){
                        if (AllocateOrderStatus.CLOSED.getValue().equals(allocateOrderDetail.getStatus())){
                            allocateOrderDetailsClosed.add(allocateOrderDetail);
                        }else {
                            allocateOrderDetails.add(allocateOrderDetail);
                        }
                    }
                    //判断是否已关闭
                    if (allocateOrderDetailsClosed.size()!=result.getResult().size()){
                        isClosed = false;
                    }
                    for (AllocateOrderDetail allocateOrderDetail : allocateOrderDetails) {
                        //判断是否已发货
                        if (!AllocateOrderStatus.Shipped.getValue().equals(allocateOrderDetail.getStatus())) {
                            isShipped = false;
                        }
                        //判断是否已收货
                        if (!AllocateOrderStatus.Received.getValue().equals(allocateOrderDetail.getStatus())) {
                            isReceived = false;
                        }
                        //判断是否代发货状态
                        if (!AllocateOrderStatus.Shipment_Processing.getValue().equals(allocateOrderDetail.getStatus())){
                            isShipmentProcessing = false;
                        }
                        //判断是否部分收货
                        if (AllocateOrderStatus.Part_Received.getValue().equals(allocateOrderDetail.getStatus()) || AllocateOrderStatus.Received.getValue().equals(allocateOrderDetail.getStatus())) {
                            isPartReceived = true;
                        }
                    }
                    //判断是否关闭
                    if (isClosed) {
                        allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
                    } else {
                        //判断是否已发货
                        if (isShipped) {
                            allocateOrder.setStatus(AllocateOrderStatus.Shipped.getValue());
                        } else {
                            //判断是否已收货
                            if (isReceived) {
                                allocateOrder.setStatus(AllocateOrderStatus.Received.getValue());
                            } else {
                                //判断是否代发货
                                if (isShipmentProcessing){
                                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                                }else {
                                    //判断是否部分收货
                                    if (isPartReceived) {
                                        allocateOrder.setStatus(AllocateOrderStatus.Part_Received.getValue());
                                    } else {
                                        allocateOrder.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //把请求过的加进去
            allocateOrder.setShipOutMaterialCertificateId(InfoUtil.splice(allocateOrder.getShipOutMaterialCertificateId(),
                    request.getOutMaterialCertificateId()));
            allocateOrder.setGmt_modified(new Date());
            allocateOrderService.updateAllocateOrder(allocateOrder);
        }
        response.setCode(request.getId());

        return response;
    }


    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public AllocateOrderCancelShippedResponse
    cancelShipped(AllocateOrderCancelShippedRequest request) {
        // TODO: 2021/12/3 加事务 @余红伟
        AllocateOrderCancelShippedResponse response = new AllocateOrderCancelShippedResponse();
        if (request == null || StringUtils.isBlank(request.getId())
                || CollectionUtils.isEmpty(request.getShippedScItemDTOS())) {
            throw new FacadeException("OTS-03-005-00-15-069");
        }
        if (StringUtils.isBlank(request.getOutMaterialCertificateId())) {
            throw new FacadeException("OTS-03-005-00-15-076");
        }
        List<AllocateOrderCancelShippedScItemDTO> shipScItems = request.getShippedScItemDTOS().stream()
                .filter(x -> StringUtils.isNotBlank(x.getShipQuantity()) && StringUtils.isNotBlank(x.getScItemId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(shipScItems)) {
            throw new FacadeException("OTS-03-005-00-15-036");
        }
        boolean illegal = shipScItems.stream().anyMatch(x -> InfoUtil.getInt(x.getShipQuantity()) <= 0);
        if (illegal) {
            throw new FacadeException("OTS-03-005-00-15-037");
        }
        LoadAllocateOrderRequest loadAllocateOrderRequest = new LoadAllocateOrderRequest();
        loadAllocateOrderRequest.setId(request.getId());
        AllocateOrder allocateOrder = allocateOrderService.loadAllocateOrder(loadAllocateOrderRequest);
        if (allocateOrder == null) {
            throw new FacadeException("OTS-03-005-00-15-063");
        }

        //校验物料凭证号是否请求过了.
        boolean checkOut = InfoUtil.checkContain(allocateOrder.getCancelShipOutMaterialCertificateId(),
                request.getOutMaterialCertificateId());
        if (checkOut) {
            log.error("调拨单撤销发货请求重复:{}", JSON.toJSONString(request));
            return response;
        }
        //判断是否是电商调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(allocateOrder.getReceiveOrgId());
        //电商调拨单 聚合 scItemId - 外部行号
        // 聚合相同scItemId的数量
        handleCancelShippedScItemData(shipScItems,isECommerceOrder);
        /**
         * 把收发货的状态 进行一个回退. 只要有回退 那主单/子单就是部分发货.
         * 回退后 发货数量 > 0  部分发货 发货时间不改动
         *      发货数量 <= 0 待发货 发货时间为空
         */
        Set<Integer> status = Sets.newHashSet();
        for (AllocateOrderCancelShippedScItemDTO scItemDTO : shipScItems) {
            AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
            listRequest.setAllocateOrderId(Long.valueOf(request.getId()));
            if (isECommerceOrder){
                listRequest.setOutAllocateOrderLineId(scItemDTO.getOutAllocateOrderLineId());
            }else {
                listRequest.setScItemId(scItemDTO.getScItemId());
            }
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
            log.info("AllocateOrderWriteRepositoryImpl.cancelShipped.getDetailResult,request:{},res:{}",
                    JSON.toJSONString(request),JSON.toJSONString(result));
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                AllocateOrderDetail orderDetail = result.getResult().get(0);
                if (orderDetail.getShipQuantity() == null) {
                    orderDetail.setShipQuantity(0);
                }
                Integer shipQuantity = orderDetail.getShipQuantity();
                Integer cancel = InfoUtil.getInt(scItemDTO.getShipQuantity());
                Integer sum = shipQuantity - cancel;
                orderDetail.setShipQuantity(sum);
                //2022.03.14更改,如果是已关闭的不做状态处理
                if (!Objects.equals(orderDetail.getStatus(),AllocateOrderStatus.CLOSED.getValue())){
                    if (sum > 0) {
                        orderDetail.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                    } else {
                        orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        orderDetail.setShipTime(new Date(0));
//                    orderDetail.setShipTime(null);
                    }
                }else {
                    if (sum <=0){
                        orderDetail.setShipTime(new Date(0));
                    }
                }
                status.add(orderDetail.getStatus());
                orderDetail.setGmt_modified(new Date());
                //防止004其他接口的影响
                orderDetail.setReceiveTime(null);
                orderDetail.setReceiveQuantity(null);
                orderDetail.setDeliveryQuantity(null);
                orderDetail.setDeliveryDate(null);
                log.info("AllocateOrderWriteRepositoryImpl.cancelShipped.updateAllocateOrderDetail,{}",JSON.toJSONString(orderDetail));
                allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
            }else {
                throw new FacadeException("OTS-03-005-00-15-106");
            }
        }
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        //子单有过状态更新 且库里也有数据 3.15 并且不是关闭状态
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())
                && CollectionUtils.isNotEmpty(status) &&
            !Objects.equals(allocateOrder.getStatus(),AllocateOrderStatus.CLOSED.getValue())) {
//            boolean allDone =
//                    result.getResult().stream().filter(x-> !(Objects.equals(x.getClose(),Boolean.TRUE)))
//                            .allMatch(y-> AllocateOrderStatus.Shipment_Processing.getValue().equals(y.getStatus()));
            /**
             * 1.1、如果行状态全部是已发货、主单状态变为已发货状态
             * 1.2、行状态如果全部是已收货状态，主单状态改为已收货状态
             * 2、行状态有一个已收货或者部分收货状态，主单就是部分收货状态
             *
             */
            //是否已发货
            boolean isShipped = true;
            //是否已收货
            boolean isReceived = true;
            //是否部分收货
            boolean isPartReceived = false;
            //是否已关闭状态
            boolean isClosed = true;
            //是否代发货状态
            boolean isShipmentProcessing = true;
            List<AllocateOrderDetail> allocateOrderDetails = new ArrayList<>();
            List<AllocateOrderDetail> allocateOrderDetailsClosed = new ArrayList<>();
            for (AllocateOrderDetail allocateOrderDetail : result.getResult()){
                if (AllocateOrderStatus.CLOSED.getValue().equals(allocateOrderDetail.getStatus())){
                    allocateOrderDetailsClosed.add(allocateOrderDetail);
                }else {
                    allocateOrderDetails.add(allocateOrderDetail);
                }
            }
            //判断是否已关闭
            if (allocateOrderDetailsClosed.size()!=result.getResult().size()){
                isClosed = false;
            }
            for (AllocateOrderDetail allocateOrderDetail : allocateOrderDetails) {
                //判断是否已发货
                if (!AllocateOrderStatus.Shipped.getValue().equals(allocateOrderDetail.getStatus())) {
                    isShipped = false;
                }
                //判断是否已收货
                if (!AllocateOrderStatus.Received.getValue().equals(allocateOrderDetail.getStatus())) {
                    isReceived = false;
                }
                //判断是否代发货状态
                if (!AllocateOrderStatus.Shipment_Processing.getValue().equals(allocateOrderDetail.getStatus())){
                    isShipmentProcessing = false;
                }
                //判断是否部分收货
                if (AllocateOrderStatus.Part_Received.getValue().equals(allocateOrderDetail.getStatus()) || AllocateOrderStatus.Received.getValue().equals(allocateOrderDetail.getStatus())) {
                    isPartReceived = true;
                }
            }
            //判断是否关闭
            if (isClosed) {
                allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
            } else {
                //判断是否已发货
                if (isShipped) {
                    allocateOrder.setStatus(AllocateOrderStatus.Shipped.getValue());
                } else {
                    //判断是否已收货
                    if (isReceived) {
                        allocateOrder.setStatus(AllocateOrderStatus.Received.getValue());
                    } else {
                        //判断是否代发货
                        if (isShipmentProcessing){
                            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        }else {
                            //判断是否部分收货
                            if (isPartReceived) {
                                allocateOrder.setStatus(AllocateOrderStatus.Part_Received.getValue());
                            } else {
                                allocateOrder.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                            }
                        }
                    }
                }
            }

            //把请求过的加进去
            allocateOrder.setCancelShipOutMaterialCertificateId(InfoUtil.splice(allocateOrder.getCancelShipOutMaterialCertificateId(),
                    request.getOutMaterialCertificateId()));
            allocateOrderService.updateAllocateOrder(allocateOrder);
        }
        response.setCode(request.getId());
        return response;
    }

    /**
     * 收货接口
     *
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderReceivedResponse received(AllocateOrderReceivedRequest request) {
        AllocateOrderReceivedResponse response = new AllocateOrderReceivedResponse();
        if (request == null || StringUtils.isBlank(request.getId())
                || CollectionUtils.isEmpty(request.getReceivedScItemDTOS())) {
            throw new FacadeException("OTS-03-005-00-15-070");
        }
        if (StringUtils.isBlank(request.getOutMaterialCertificateId())) {
            throw new FacadeException("OTS-03-005-00-15-076");
        }
        List<AllocateOrderReceivedScItemDTO> receiveScItems = request.getReceivedScItemDTOS().stream().filter(x ->
                        StringUtils.isNotBlank(x.getReceiveQuantity()) && StringUtils.isNotBlank(x.getScItemId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(receiveScItems)) {
            throw new FacadeException("OTS-03-005-00-15-074");
        }
        boolean illegal = receiveScItems.stream().anyMatch(x -> InfoUtil.getInt(x.getReceiveQuantity()) <= 0);
        if (illegal) {
            throw new FacadeException("OTS-03-005-00-15-020");
        }
        LoadAllocateOrderRequest loadAllocateOrderRequest = new LoadAllocateOrderRequest();
        loadAllocateOrderRequest.setId(request.getId());
        AllocateOrder allocateOrder = allocateOrderService.loadAllocateOrder(loadAllocateOrderRequest);
        if (allocateOrder == null) {
            throw new FacadeException("OTS-03-005-00-15-064");
        }
        //校验物料凭证号是否请求过了.
        boolean checkOut = InfoUtil.checkContain(allocateOrder.getReceiveOutMaterialCertificateId(),
                request.getOutMaterialCertificateId());
        if (checkOut) {
            log.error("调拨单发货请求重复:{}", JSON.toJSONString(request));
            return response;
        }
        //电商调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(allocateOrder.getReceiveOrgId());
        // 聚合相同scItemId的数量 / 电商的聚合外部行号
        handleReceivedScItemData(receiveScItems,isECommerceOrder);
        log.info("AllocateOrderWriteRepositoryImpl.received.handle:{}",JSON.toJSONString(receiveScItems));
        Set<Integer> status = Sets.newHashSet();
        for (AllocateOrderReceivedScItemDTO scItemDTO : receiveScItems) {
            AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
            listRequest.setAllocateOrderId(Long.valueOf(request.getId()));
            if (isECommerceOrder){
                listRequest.setOutAllocateOrderLineId(scItemDTO.getOutAllocateOrderLineId());
            }else {
                listRequest.setScItemId(scItemDTO.getScItemId());
            }
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
            log.info("AllocateOrderWriteRepositoryImpl.received.getDetailResult,{}",JSON.toJSONString(result));
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                AllocateOrderDetail orderDetail = result.getResult().get(0);
                if (orderDetail.getReceiveQuantity() == null) {
                    orderDetail.setReceiveQuantity(0);
                }
                Integer receiveQuantity = orderDetail.getReceiveQuantity();
                Integer add = InfoUtil.getInt(scItemDTO.getReceiveQuantity());
                Integer sum = receiveQuantity + add;
                orderDetail.setReceiveQuantity(sum);
                // 收货时的逻辑判断
                Integer quantity = InfoUtil.getInt(orderDetail.getQuantity());

                //2021.03.14 关闭的收发货不用影响状态
                if (!Objects.equals(orderDetail.getStatus(),AllocateOrderStatus.CLOSED.getValue())){
                    if (quantity > sum) {
                        orderDetail.setStatus(AllocateOrderStatus.Part_Received.getValue());
                    } else {
                        orderDetail.setStatus(AllocateOrderStatus.Received.getValue());
                    }
                }

                if (StringUtils.isNotBlank(request.getPostingTime())) {
                    Date postTime = TimeUtil.parseSimpleDateFormat(request.getPostingTime());
                    orderDetail.setReceiveTime(postTime);
                } else {
                    orderDetail.setReceiveTime(new Date());
                }
                status.add(orderDetail.getStatus());

                orderDetail.setGmt_modified(new Date());
                //防止004的其他影响
                orderDetail.setShipQuantity(null);
                orderDetail.setShipTime(null);
                orderDetail.setDeliveryDate(null);
                orderDetail.setDeliveryQuantity(null);
                log.info("AllocateOrderWriteRepositoryImpl.received.updateAllocateOrderDetail,{}",JSON.toJSONString(orderDetail));
                allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
            }else {
                throw new FacadeException("OTS-03-005-00-15-106");
            }
        }
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        //子单有过状态更新 且库里也有数据
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())
                && CollectionUtils.isNotEmpty(status)
            && !Objects.equals(allocateOrder.getStatus(),AllocateOrderStatus.CLOSED.getValue())) {
            boolean allDone =
                    result.getResult().stream().filter(x -> !(Objects.equals(x.getClose(), Boolean.TRUE)))
                            .allMatch(y -> AllocateOrderStatus.Received.getValue().equals(y.getStatus()));
            //如果明细中全是收货, 那就是已收货, 如果否则 就部分收货
            if (allDone) {
                allocateOrder.setStatus(AllocateOrderStatus.Received.getValue());
            } else {
                allocateOrder.setStatus(AllocateOrderStatus.Part_Received.getValue());
            }
            //把请求过的加进去
            allocateOrder.setReceiveOutMaterialCertificateId(InfoUtil.splice(allocateOrder.getReceiveOutMaterialCertificateId(),
                    request.getOutMaterialCertificateId()));
            allocateOrder.setGmt_modified(new Date());
            allocateOrderService.updateAllocateOrder(allocateOrder);
        }
        response.setCode(request.getId());
        return response;
    }

    @Override
    @Deprecated
    public String save(AllocateOrderSDO allocateOrderSDO) {
        if (allocateOrderSDO != null) {
            AllocateOrder allocateOrder = JsonUtil.convert(allocateOrderSDO, AllocateOrder.class);
            allocateOrder.setGmt_create(null);
            allocateOrder.setGmt_modified(null);
            CreateAllocateOrderResponse createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);
            return String.valueOf(createAllocateOrderResponse.getLastInsertId());
        }
        return null;
    }

    @Override
    @Deprecated
    public List<String> save(List<AllocateOrderDetailSDO> detailSDOS) {
        List<String> list = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(detailSDOS)) {
            for (AllocateOrderDetailSDO sdo : detailSDOS) {
                AllocateOrderDetail detail = JsonUtil.convert(sdo, AllocateOrderDetail.class);
                detail.setGmt_create(null);
                detail.setGmt_modified(null);
                CreateAllocateOrderDetailResponse orderDetail = allocateOrderDetailService.createAllocateOrderDetail(detail);
                if (orderDetail != null && StringUtils.isNotBlank(orderDetail.getLastInsertId())) {
                    list.add(orderDetail.getLastInsertId());
                }
            }
        }
        return list;
    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public AllocateOrderReturnOrderResponse returnOrder(AllocateOrderReturnOrderRequest request) {
        AllocateOrderReturnOrderResponse response = new AllocateOrderReturnOrderResponse();
        if (request == null || StringUtils.isBlank(request.getAllocateOrderId())
                || CollectionUtils.isEmpty(request.getAllocateOrderScItemDetailDTOS())) {
            throw new FacadeException("OTS-03-005-00-15-071");
        }
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setOutAllocateOrderId(request.getAllocateOrderId());
        Result<List<AllocateOrder>> allocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (CollectionUtils.isEmpty(allocateOrderList.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-065");
        }
        AllocateOrder allocateOrder = allocateOrderList.getResult().get(0);
        String sourceCode = allocateOrder.getCode();
        Long oldAllocateOrderId = allocateOrder.getId();
        if (allocateOrder == null) {
            throw new FacadeException("OTS-03-005-00-15-066");
        }
        String code = CodeUtil.salesCode();
        //调拨单的主键id
        String orderId = allocateOrder.getId().toString();
        allocateOrder.setCode(code);
        allocateOrder.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
        allocateOrder.setOrderReason(request.getOrderReason());
//        allocateOrder.setOrderReason();
        allocateOrder.setReturnOrder(true);
//        allocateOrder.setType(AllocateOrderTypeEnum.HEADQUARTER_SALES.getType());
        allocateOrder.setId(null);
        allocateOrder.setGmt_create(null);
        allocateOrder.setGmt_modified(null);
        allocateOrder.setOutAllocateOrderId(null);
        allocateOrder.setDocDate(InfoUtil.salesDocDate());
        allocateOrder.setExpectedDeliveryDate(InfoUtil.afterDays(allocateOrder.getDocDate(),1));
        allocateOrder.setSubmitTime(new Date());
        //发票退单的调拨单号
        allocateOrder.setSourceReturnOrderCode(sourceCode);
        allocateOrder.setOutAllocateApplyOrderId(null);
        allocateOrder.setAllocateApplyOrderId(null);
        allocateOrder.setAllocateApplyOrderCode(null);
        allocateOrder.setShipOutMaterialCertificateId(null);
        allocateOrder.setCancelReceiveOutMaterialCertificateId(null);
        allocateOrder.setCancelShipOutMaterialCertificateId(null);
        allocateOrder.setReceiveOutMaterialCertificateId(null);
        String receiveAreaId = allocateOrder.getReceiveAreaId();
        if (StringUtils.isBlank(allocateOrder.getReceiveAreaId())){
            AllocateOrderGetInOutOrderRequest allocateOrderGetInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
            allocateOrderGetInOutOrderRequest.setAllocateOrderId(orderId);
            allocateOrderGetInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
            allocateOrderGetInOutOrderRequest.setSize(MAX_PAGE_SIZE);
            GetListOutinForAllocationResponse listOutinForAllocation = otsUnifiedInventoryService.getListOutinForAllocation(allocateOrderGetInOutOrderRequest);
            String getReceiveAreaId = getReceiveAreaId(listOutinForAllocation);
            if (StringUtils.isNotBlank(getReceiveAreaId)){
                receiveAreaId = getReceiveAreaId;
            }
        }

        CreateAllocateOrderResponse res = allocateOrderService.createAllocateOrder(allocateOrder);
        if (res == null || null == res.getLastInsertId()) {
            throw new FacadeException("OTS-03-005-00-15-073");
        }
        response.setAllocateOrderId(String.valueOf(res.getLastInsertId()));
        int i = 1;
        for (AllocateOrderScItemDetailDTO dto : request.getAllocateOrderScItemDetailDTOS()) {
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderId(oldAllocateOrderId);
            allocateOrderDetailLoadListRequest.setScItemId(dto.getScItemId());
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            if (result == null || CollectionUtils.isEmpty(result.getResult())) {
                continue;
            }
            AllocateOrderDetail allocateOrderDetail = result.getResult().get(0);
            allocateOrderDetail.setId(null);
            allocateOrderDetail.setConfirmTime(null);
            allocateOrderDetail.setDeliveryDate(null);
            allocateOrderDetail.setReceiveTime(null);
            allocateOrderDetail.setOutWarehouseDate(null);
            allocateOrderDetail.setOutWarehouseProductDate(null);
            allocateOrderDetail.setReceiveDate(null);
            allocateOrderDetail.setOutAllocateOrderLineId(null);
            allocateOrderDetail.setExchangeAmt(null);
            allocateOrderDetail.setSendBackRequired(false);
            allocateOrderDetail.setOutAllocateApplyOrderLineId(null);
            allocateOrderDetail.setSubTotalAmount(null);
            allocateOrderDetail.setDeliveryQuantity(null);
            allocateOrderDetail.setDeliveryDate(null);
            allocateOrderDetail.setFeatures(null);
            allocateOrderDetail.setGiftQuantity(null);
            allocateOrderDetail.setTaxRate(null);
            allocateOrderDetail.setCloseReason(null);
            allocateOrderDetail.setClose(false);
            allocateOrderDetail.setCloseCode(null);


            allocateOrderDetail.setAllocateApplyOrderLineId(null);
            allocateOrderDetail.setOutAllocateOrderLineId(null);
            allocateOrderDetail.setGmt_create(null);
            allocateOrderDetail.setGmt_modified(null);
            allocateOrderDetail.setAllocateOrderId(res.getLastInsertId());
            allocateOrderDetail.setAllocateOrderCode(code);
            allocateOrderDetail.setQuantity(dto.getQuantity());
            //退单 确认数量 = 订单数量
            allocateOrderDetail.setConfirmQuantity(dto.getQuantity());
            allocateOrderDetail.setRemarks(dto.getRemarks());

            String scItemId = dto.getScItemId();
            GetListWarehouseStock2Request getListWarehouseStock2Request = new GetListWarehouseStock2Request();
//            getListWarehouseStock2Request.setWarehouseAreaId(allocateOrder.getShipAreaId());
            getListWarehouseStock2Request.setWarehouseAreaId(receiveAreaId);
            getListWarehouseStock2Request.setType("1");
            if (StringUtils.isNotBlank(scItemId)){
                getListWarehouseStock2Request.setGoodsId(scItemId);
            }
            Result<List<WarehouseInventory>> listWarehouseStock2 = otsUnifiedInventoryService.getListWarehouseStock2(getListWarehouseStock2Request);
            if (listWarehouseStock2 != null && CollectionUtils.isNotEmpty(listWarehouseStock2.getResult())){
//                WarehouseInventory warehouseInventory = listWarehouseStock2.getResult().stream().filter(x -> Objects.equals(x.getGoodsCode(), allocateOrderDetail.getScItemCode()))
//                        .findFirst().orElse(null);
                WarehouseInventory warehouseInventory = listWarehouseStock2.getResult().get(0);
                if (warehouseInventory != null){
                    if (CollectionUtils.isNotEmpty(warehouseInventory.getDoms())){
                        String dom = warehouseInventory.getDoms().stream().filter(x -> StringUtils.isNotBlank(x.getDom()))
                                .sorted(Comparator.comparing(WarehouseInventoryDoms::getDom)).findFirst().get().getDom();
                        allocateOrderDetail.setExpectedProduceDate(TimeUtil.parseYYYY_MM_dd(dom));
                    }
                }
            }
//            allocateOrderDetail.setExpectedProduceDate(dto.getExpectedProduceDate());
            allocateOrderDetail.setReturnOrder(true);
            //记录发票号和发票行号
            allocateOrderDetail.setInvoiceLineNo(dto.getInvoiceLineNo());
            allocateOrderDetail.setInvoiceNo(dto.getInvoiceNo());
            allocateOrderDetail.setStatus(AllocateOrderStatus.WAIT_PUSH.getValue());
            allocateOrderDetail.setShipQuantity(null);
            allocateOrderDetail.setShipTime(null);
            allocateOrderDetail.setReceiveTime(null);
            allocateOrderDetail.setReceiveQuantity(null);
            allocateOrderDetail.setOutWarehouseDate(null);
            allocateOrderDetail.setOutWarehouseProductDate(null);
            allocateOrderDetail.setLineNo(i);
//            allocateOrderDetail.setQuantity(dto.getQuantity());
            allocateOrderDetailService.createAllocateOrderDetail(allocateOrderDetail);
            i++;
        }
        response.setCode(code);
        return response;
    }

    //获取收货仓id
    String getReceiveAreaId(GetListOutinForAllocationResponse response){
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            for (Object data : response.getResult()) {
                if (data == null){
                    continue;
                }
                JSONObject js = JSONObject.parseObject(JSON.toJSONString(data));
                if (js == null){
                    continue;
                }
                String type = js.getString("mainOrderType");
                //1入库 2出库
                if ("1".equals(type) || "1.0".equals(type)){
                    String warehouseAreaId = js.getString("warehouseAreaId");
                    if (StringUtils.isNotBlank(warehouseAreaId)){
                        return warehouseAreaId;
                    }
                }
            }
        }
        return null;
    }

    public static void set(AllocateOrder allocateOrder, AllocateOrderSDO allocateOrderSDO) {
        allocateOrder.setSapCostCenter(allocateOrderSDO.getSapCostCenter());
        allocateOrder.setOrderReason(allocateOrderSDO.getOrderReason());
        allocateOrder.setSapRefPoNo(allocateOrderSDO.getSapRefPoNo());
        allocateOrder.setTypeCard(allocateOrderSDO.getTypeCard());
        allocateOrder.setFounder(allocateOrderSDO.getFounder());
        allocateOrder.setConfirmQuantity(allocateOrderSDO.getConfirmQuantity());
        allocateOrder.setCreateTime(allocateOrderSDO.getCreateTime());
        allocateOrder.setGmt_modified(allocateOrderSDO.getGmtModified());
        allocateOrder.setUpdater(allocateOrderSDO.getUpdater());
        allocateOrder.setLastUpdateUser(allocateOrderSDO.getLastUpdateUser());
        allocateOrder.setExpectedDeliveryDate(allocateOrderSDO.getExpectedDeliveryDate());
        allocateOrder.setCompleteTime(allocateOrderSDO.getCompleteTime());
        allocateOrder.setShipAreaId(allocateOrderSDO.getShipAreaId());
        allocateOrder.setShipWarehouseId(allocateOrderSDO.getShipWarehouseId());
        allocateOrder.setReceiveAreaId(allocateOrderSDO.getReceiveAreaId());
        allocateOrder.setReceiveWarehouseId(allocateOrderSDO.getReceiveWarehouseId());
        allocateOrder.setProductGroup(allocateOrderSDO.getProductGroup());
        allocateOrder.setOutAllocateApplyOrderId(allocateOrderSDO.getOutAllocateApplyOrderId());
        allocateOrder.setOutAllocateOrderId(allocateOrderSDO.getOutAllocateOrderId());
        allocateOrder.setAllocateApplyOrderId(allocateOrderSDO.getAllocateApplyOrderId());
        allocateOrder.setSapChannel(allocateOrderSDO.getSapChannel());
        allocateOrder.setSapSalesOrgId(allocateOrderSDO.getSapSalesOrgId());
        allocateOrder.setCustomer(allocateOrderSDO.getCustomer());
        allocateOrder.setApplyOrgId(allocateOrderSDO.getApplyOrgId());
        allocateOrder.setFeatures(allocateOrderSDO.getFeatures());
        allocateOrder.setType(allocateOrderSDO.getType());
//            allocateOrder.setStatus();
        allocateOrder.setCreateTime(allocateOrderSDO.getCreateTime());
        allocateOrder.setShipMethod(allocateOrderSDO.getShipMethod());
        allocateOrder.setRemark(allocateOrderSDO.getRemark());
        allocateOrder.setSendBackRequired(allocateOrderSDO.getSendBackRequired());
        allocateOrder.setConfirmTime(allocateOrderSDO.getConfirmTime());
        allocateOrder.setGmt_modified(new Date());
    }

    public static void set(AllocateOrder order, AllocateOrderSalesOrderSyncRequest request) {
        order.setOutAllocateOrderId(request.getOutAllocateApplyOrderId());
        order.setSapCostCenter(request.getSapCostCenter());
        order.setOrderReason(request.getOrderReason());
        order.setSapRefPoNo(request.getSapRefPoNo());
        order.setTypeCard(request.getTypeCard());
        order.setFounder(request.getFounder());
        order.setConfirmQuantity(request.getConfirmQuantity());
        order.setCreator(request.getCreator());
        order.setUpdater(request.getUpdater());
        order.setCompleteTime(request.getCompleteTime());
        order.setShipMethod(request.getShipMethod());
        order.setShipAreaId(request.getShipAreaId());
        order.setShipWarehouseId(request.getShipWarehouseId());
//        order.setReceiveWarehouseId(request.getReceiveWarehouseId());
//        order.setReceiveAreaId(request.getReceiveAreaId());
        order.setProductGroup(request.getProductGroup());
        order.setOutAllocateApplyOrderId(request.getOutAllocateApplyOrderId());
        order.setAllocateApplyOrderId(request.getAllocateApplyOrderId());
        order.setSapChannel(request.getSapChannel());
        order.setSapSalesOrgId(request.getSapSalesOrgId());
        order.setCustomer(request.getCustomer());
//        order.setApplyOrgId(request.getApplyOrgId());
        order.setFeatures(request.getFeatures());
        order.setCreateTime(request.getCreateTime());
        order.setLastUpdateUser(request.getLastUpdateUser());
        order.setDocDate(request.getDocDate());
        order.setShipMethod(request.getShipMethod());
//        order.setTotalQuantity(request.getTotalQuantity());
        order.setDiscount(request.getDiscount());
        order.setTotalAmount(request.getTotalAmount());
        order.setRemark(request.getRemark());
        order.setSendBackRequired(request.getSendBackRequired());
        order.setConfirmTime(request.getConfirmTime());

    }

    /**
     * 获取单个客户信息
     *
     * @param code
     * @return
     */
    @Override
    public AllocateOrderGetCustomerResponse getCustomer(String code) {
        PageQueryAddressListRequest request = new PageQueryAddressListRequest();
        if (StringUtils.isNotBlank(code)) {
            request.setCustomerCode(code);
        }
        PageQueryAddressListResponse response = otsPlatformEnhanceService.pageQueryAddressList(request);
        if (response == null || response.getResult() == null) {
            return null;
        }
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(response.getResult()));
        if (array == null || array.size() == 0) {
            return null;
        }
        JSONObject object = array.getJSONObject(0);
        AllocateOrderGetCustomerResponse r = new AllocateOrderGetCustomerResponse();
        r.setCustomerName(object.getString("customerName"));
        r.setCustomerAddress(object.getString("address"));
        r.setCustomerAddressName(object.getString("addressName"));
        r.setCustomer(code);
        return r;
    }

    /**
     * 同一个交货单再次请求时  更新交货数量 值不变. 可多次请求
     *
     * @param request
     * @return
     */
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderDeliveryResponse deliveredFresh(AllocateOrderDeliveryRequest request) {
        // TODO: 2021/12/3 弱依赖改成补货异常 记录日志 @余红伟
        AllocateOrderDeliveryResponse response = new AllocateOrderDeliveryResponse();
        if (StringUtils.isAllBlank(request.getOutAllocateOrderId(), request.getCode())) {
            log.info("deliveredFreshSaleOrderReturn, code:{}, outAllocateOrderId:{}", request.getCode(), request.getOutAllocateOrderId());
            return response;
        }
        //复制一下原数据
        AllocateOrderDeliveryRequest oldRequest = JsonUtil.convert(request, AllocateOrderDeliveryRequest.class);
//        if (CollectionUtils.isEmpty(request.getDeliveryScItemDTOList())){
//            return response;
//        }
        //找出触发更新操作的交货单 -> 此次对应的调拨单 -> 找到所有的调拨单 依据 调拨单号来找好了
        ConsignmentOrderLoadListRequest orderLoadListRequest = new ConsignmentOrderLoadListRequest();
//        if (StringUtils.isNotBlank(request.getOutAllocateOrderId())){
//            orderLoadListRequest.setOuterStoOrderId(InfoUtil.deleteZeroPrefix(request.getOutAllocateOrderId()));
//        }
        if (StringUtils.isNotBlank(request.getOutAllocateOrderId())) {
            orderLoadListRequest.setOuterStoOrderId(InfoUtil.deleteZeroPrefix(request.getOutAllocateOrderId()));
        }
        //未删除
        orderLoadListRequest.setStatus(1);
        //还有个调拨单号
        orderLoadListRequest.setLimit(1000);
        Result<List<ConsignmentOrder>> orderList = consignmentOrderService.loadConsignmentOrderList(orderLoadListRequest);
        if (orderList == null || CollectionUtils.isEmpty(orderList.getResult())) {
            return response;
        }
        log.info("delivery_loadConsignmentOrderList:{}",JSON.toJSONString(orderList));
        //循环获取到 不同交货单 的同一个调拨单的 子单 交货数量
        Map<String, List<AllocateOrderDeliveryScItemDTO>> map = Maps.newHashMap();
        List<AllocateOrderDeliveryScItemDTO> scItemDTOList = Lists.newArrayList();
        AllocateOrderDeliveryRequest freshRequest = new AllocateOrderDeliveryRequest();
        if (StringUtils.isNotBlank(request.getOutAllocateOrderId())) {
            freshRequest.setOutAllocateOrderId(request.getOutAllocateOrderId());
        }
        if (StringUtils.isNotBlank(request.getCode())) {
            freshRequest.setCode(request.getCode());
        }
        if (StringUtils.isNotBlank(request.getDeliveryDate())) {
            freshRequest.setDeliveryDate(request.getDeliveryDate());
        }
        if (StringUtils.isNotBlank(request.getCreateDate())) {
            freshRequest.setCreateDate(request.getCreateDate());
        }
        
        //查询调拨单 判断是否是电商的
        AllocateOrderLoadListRequest queryAllocateOrderRequest = new AllocateOrderLoadListRequest();
        if (StringUtils.isBlank(freshRequest.getOutAllocateOrderId())){
            return response;
        }
        queryAllocateOrderRequest.setOutAllocateOrderId(freshRequest.getOutAllocateOrderId());
        Result<List<AllocateOrder>> loadAllocateOrderList = allocateOrderService.loadAllocateOrderList(queryAllocateOrderRequest);
        if (loadAllocateOrderList == null || CollectionUtils.isEmpty(loadAllocateOrderList.getResult())){
            return response;
        }
        //是否电商调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(loadAllocateOrderList.getResult().get(0).getReceiveOrgId());
        for (ConsignmentOrder order : orderList.getResult()) {
            //先查出交货单下的明细
            ConsignmentOrderLineLoadListRequest lineLoadListRequest = new ConsignmentOrderLineLoadListRequest();
            lineLoadListRequest.setConsignmentOrderId(order.getId().toString());
            lineLoadListRequest.setLimit(1000);
            Result<List<ConsignmentOrderLine>> listResult = consignmentOrderLineService.loadConsignmentOrderLineList(lineLoadListRequest);
            if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
                continue;
            }
            log.info("delivery_loadConsignmentOrderLineList:{}",JSON.toJSONString(listResult));
            List<ConsignmentOrderLine> lineList;
            //电商的使用外部行号
            if (isECommerceOrder){
                lineList = listResult.getResult().stream()
                        .filter(x -> StringUtils.isNotBlank(x.getOuterStoLineId()) && StringUtils.isNotBlank(x.getQty()))
                        .filter(x -> NORMAL.equals(x.getStatus()))
                        .collect(Collectors.toList());
            }else {
                lineList = listResult.getResult().stream()
                        .filter(x -> StringUtils.isNotBlank(x.getScItemId()) &&  StringUtils.isNotBlank(x.getQty()))
                        .filter(x -> NORMAL.equals(x.getStatus()))
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(lineList)) {
                continue;
            }
            Map<String, List<ConsignmentOrderLine>> scItemMap;
            //电商调拨单使用外部行号
            if (isECommerceOrder){
                //根据行号聚合交货数量
                scItemMap = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getOuterStoLineId));
                scItemMap.forEach((k, v) -> {
                    if (CollectionUtils.isNotEmpty(v)) {
                        int sum = v.stream().map(ConsignmentOrderLine::getQty).filter(Objects::nonNull)
                                .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                        // 物料 -> 交货累计数量
                        AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
//                        scItemDTO.setScItemId(k);
                        scItemDTO.setOutAllocateOrderLineId(k);
                        scItemDTO.setDeliveryQuantity(sum + "");
                        scItemDTOList.add(scItemDTO);
                    }
                });
            }else {
                scItemMap = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getScItemId));
                scItemMap.forEach((k, v) -> {
                    if (CollectionUtils.isNotEmpty(v)) {
                        int sum = v.stream().map(ConsignmentOrderLine::getQty).filter(Objects::nonNull)
                                .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                        // 物料 -> 交货累计数量
                        AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
                        scItemDTO.setScItemId(k);
                        scItemDTO.setDeliveryQuantity(sum + "");
                        scItemDTOList.add(scItemDTO);
                    }
                });
            }
        }
        List<AllocateOrderDeliveryScItemDTO> freshScItemDTOList = Lists.newArrayList();
        //获取到某行/某物料 的交货数量
        if (CollectionUtils.isNotEmpty(scItemDTOList)) {
            Map<String, List<AllocateOrderDeliveryScItemDTO>> collect;
            if (isECommerceOrder){
                collect = scItemDTOList.stream()
                        .collect(Collectors.groupingBy(AllocateOrderDeliveryScItemDTO::getOutAllocateOrderLineId));

            }else {
                collect = scItemDTOList.stream()
                        .collect(Collectors.groupingBy(AllocateOrderDeliveryScItemDTO::getScItemId));
            }
            collect.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    int sum = v.stream().map(AllocateOrderDeliveryScItemDTO::getDeliveryQuantity).filter(Objects::nonNull)
                            .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                    AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
                    if (isECommerceOrder){
                        scItemDTO.setOutAllocateOrderLineId(k);
                    }else {
                        scItemDTO.setScItemId(k);
                    }
                    scItemDTO.setDeliveryQuantity(sum + "");
                    freshScItemDTOList.add(scItemDTO);
                }
            });
        }
        freshRequest.setDeliveryScItemDTOList(freshScItemDTOList);
        //参数 找到了调拨单  调拨物料的集合
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        if (StringUtils.isNotBlank(freshRequest.getCode())) {
            allocateOrderLoadListRequest.setCode(freshRequest.getCode());
        } else if (StringUtils.isNotBlank(freshRequest.getOutAllocateOrderId())) {
            allocateOrderLoadListRequest.setOutAllocateOrderId(freshRequest.getOutAllocateOrderId());
        }
        allocateOrderLoadListRequest.setLimit(1000);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return response;
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        if (CollectionUtils.isEmpty(freshRequest.getDeliveryScItemDTOList())) {
            return response;
        }
        //获取到旧调拨单sdo
        AllocateOrderRequest allocateOrderRequest = new AllocateOrderRequest();
        allocateOrderRequest.setAllocateOrderId(allocateOrder.getId().toString());
        AllocateOrderWithOrderDetailsSDO oldSDO = allocateOrderReadRepository.get(allocateOrderRequest);
        Date createDate = new Date();

//        if (StringUtils.isNotBlank(freshRequest.getDeliveryDate())){
//            deliveryDate = TimeUtil.parseSimpleDateFormat(freshRequest.getDeliveryDate());
//        }
        if (StringUtils.isNotBlank(freshRequest.getCreateDate())) {
            createDate = TimeUtil.parseSimpleDateFormat(freshRequest.getCreateDate());
        }
        //添加进货品id 用于后面循环的 暂时用货品编码

        // 交货数量的更新问题, 因为交货单存在删除行的操作 所以要循环现有的明细行 再去匹配交货单的明细行
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
            for (AllocateOrderDetail allocateOrderDetail : result.getResult()) {
                if (allocateOrderDetail == null) {
                    continue;
                }
                //找到符合的货品
                List<AllocateOrderDeliveryScItemDTO> targetList;
                //电商的根据外部行号
                if (isECommerceOrder){
                    targetList = freshRequest.getDeliveryScItemDTOList().stream()
                            .filter(x-> Objects.equals(InfoUtil.deleteZeroPrefix(allocateOrderDetail.getOutAllocateOrderLineId()),x.getOutAllocateOrderLineId()))
                            .collect(Collectors.toList());
                }else {
                    targetList = freshRequest.getDeliveryScItemDTOList().stream()
                            .filter(x -> Objects.equals(allocateOrderDetail.getScItemId(), x.getScItemId()))
                            .collect(Collectors.toList());
                }
                if (CollectionUtils.isNotEmpty(targetList)) {
                    AllocateOrderDeliveryScItemDTO scItemDTO = targetList.get(0);
                    allocateOrderDetail.setDeliveryQuantity(scItemDTO.getDeliveryQuantity());
//                    allocateOrderDetail.setDeliveryDate(deliveryDate);
                    //实际的交货日期用的是交货凭证的创建日期;
                    // 如果当前请求里有交货刷新交货日期.
                    if (CollectionUtils.isNotEmpty(oldRequest.getDeliveryScItemDTOList())) {
                        boolean needDelivery;
                        if (isECommerceOrder){
                            needDelivery = oldRequest.getDeliveryScItemDTOList().stream()
                                    .anyMatch(x -> Objects.equals(x.getOutAllocateOrderLineId(),InfoUtil.deleteZeroPrefix(allocateOrderDetail.getOutAllocateOrderLineId())));
                        }else {
                            needDelivery = oldRequest.getDeliveryScItemDTOList().stream()
                                    .anyMatch(x -> Objects.equals(x.getScItemCode(), allocateOrderDetail.getScItemCode()));
                        }
                        if (needDelivery) {
                            allocateOrderDetail.setDeliveryDate(createDate);
                        }
                    }
                } else {
                    allocateOrderDetail.setDeliveryQuantity("");
                    allocateOrderDetail.setDeliveryDate(new Date(0));
                }
                //防止交货导致收发货数量问题
                allocateOrderDetail.setShipQuantity(null);
                allocateOrderDetail.setReceiveQuantity(null);
                allocateOrderDetail.setShipTime(null);
                allocateOrderDetail.setReceiveTime(null);
                allocateOrderDetail.setStatus(null);
                allocateOrderDetail.setGmt_modified(new Date());
                allocateOrderDetailService.updateAllocateOrderDetail(allocateOrderDetail);

            }
        }

//        for (AllocateOrderDeliveryScItemDTO scItemDTO : freshRequest.getDeliveryScItemDTOList()) {
//            AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
//            detailLoadListRequest.setAllocateOrderId(allocateOrder.getId().toString());
////            AllocateOrderDetailBatchGetScItemResponse scItemResponse = map.get(scItemDTO.getScItemCode());
////            if (scItemResponse == null || StringUtils.isBlank(scItemResponse.getScItemId())) {
////                continue;
////            }
//            detailLoadListRequest.setScItemId(scItemDTO.getScItemId());
//            detailLoadListRequest.setAllocateOrderId(allocateOrder.getId().toString());
//            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
//            if (result == null || CollectionUtils.isEmpty(result.getResult())){
//                continue;
//            }
//            AllocateOrderDetail allocateOrderDetail = result.getResult().get(0);
////            allocateOrderDetail.setDeliveryQuantity(InfoUtil.addNoPoint(allocateOrderDetail.getDeliveryQuantity(),
////                    scItemDTO.getDeliveryQuantity()));
//            allocateOrderDetail.setDeliveryQuantity(scItemDTO.getDeliveryQuantity());
//            allocateOrderDetail.setDeliveryDate(deliveryDate);
//            allocateOrderDetail.setGmt_modified(new Date());
//            allocateOrderDetailService.updateAllocateOrderDetail(allocateOrderDetail);
//        }
        AllocateOrderWithOrderDetailsSDO sdo = allocateOrderReadRepository.get(allocateOrderRequest);
        saveDocumentLog(oldSDO, sdo, Integer.parseInt(AllocateApplyOrderOperationTypeEnum.DELIVERED.getValue()),
                OperatorType.INNER_INTERFACE.getOperatorType());
        response.setCode(allocateOrder.getCode());
        response.setId(allocateOrder.getId().toString());
        try{
            if (StringUtils.isNotBlank(allocateOrder.getAllocateApplyOrderId())){
                deliveredAllocateApplyOrder(AllocateApplyOrderDeliveredRequest.builder()
                        .allocateApplyOrderId(Long.valueOf(allocateOrder.getAllocateApplyOrderId())).build());
            }
        }catch (Throwable e){
            log.error("deliveredAllocateApplyOrder_error",e);
        }

        return response;

    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public AllocateOrderCancelDeliveredResponse cancelDelivered(AllocateOrderCancelDeliveredRequest allocateOrderCancelDeliveredRequest) {
        AllocateOrderCancelDeliveredResponse response = new AllocateOrderCancelDeliveredResponse();
        if (allocateOrderCancelDeliveredRequest == null || StringUtils.isBlank(allocateOrderCancelDeliveredRequest.getDeliveryOrderId())) {
            return response;
        }
        //获取删除的交货单
        ConsignmentOrderLoadListRequest request = new ConsignmentOrderLoadListRequest();
        request.setOuterDeliveryOrderId(SapAndCrmFieldDealUtils.generateIdField(allocateOrderCancelDeliveredRequest.getDeliveryOrderId()));
        Result<List<ConsignmentOrder>> loadConsignmentOrderList = consignmentOrderService.loadConsignmentOrderList(request);
        if (loadConsignmentOrderList == null || CollectionUtils.isEmpty(loadConsignmentOrderList.getResult())) {
            return response;
        }
        List<String> outCodes = loadConsignmentOrderList.getResult().stream().filter(x -> StringUtils.isNotBlank(x.getOuterStoOrderId()))
                .map(ConsignmentOrder::getOuterStoOrderId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(outCodes)) {
            return response;
        }
        //获取到调拨单号
        String code = outCodes.get(0);
        AllocateOrderRequest allocateOrderRequest = new AllocateOrderRequest();
        String outAllocateOrderId = InfoUtil.addZeroPrefix(code);
        allocateOrderRequest.setOutAllocateOrderId(outAllocateOrderId);
        AllocateOrderWithOrderDetailsSDO oldSDO = allocateOrderReadRepository.get(allocateOrderRequest);
        if (Objects.isNull(oldSDO)||Objects.isNull(oldSDO.getAllocateOrderSDO())||StringUtils.isBlank(oldSDO.getAllocateOrderSDO().getCode())){
            return response;
        }

        ConsignmentOrderLoadListRequest orderLoadListRequest = new ConsignmentOrderLoadListRequest();
        orderLoadListRequest.setOuterStoOrderId(code);
        //未删除
        orderLoadListRequest.setStatus(1);
        orderLoadListRequest.setLimit(MAX_PAGE_SIZE);
        //还有个调拨单号
        Result<List<ConsignmentOrder>> orderList = consignmentOrderService.loadConsignmentOrderList(orderLoadListRequest);
        //如果找不到 就把 交货数量 交货时间撤回去 ，调拨单也不能为空

        if (orderList == null || CollectionUtils.isEmpty(orderList.getResult())) {
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderCode(oldSDO.getAllocateOrderSDO().getCode());
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                for (AllocateOrderDetail detail : result.getResult()) {
                    //TODO 因为纪元现在的自身方法不支持设置nul
                    detail.setDeliveryDate(new Date(0));
                    detail.setDeliveryQuantity("");
//                    detail.setDeliveryQuantity(null);
                    detail.setGmt_modified(new Date());
                    allocateOrderDetailService.updateAllocateOrderDetail(detail);
                }
                AllocateOrderWithOrderDetailsSDO sdo = allocateOrderReadRepository.get(allocateOrderRequest);
                saveDocumentLog(oldSDO, sdo, Integer.parseInt(AllocateApplyOrderOperationTypeEnum.CANCELRECEIVED.getValue()),
                        OperatorType.INNER_INTERFACE.getOperatorType());
            }
            try{
                AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
                allocateOrderLoadListRequest.setCode(oldSDO.getAllocateOrderSDO().getCode());
                Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult()) &&
                        StringUtils.isNotBlank(listResult.getResult().get(0).getAllocateApplyOrderId())){
                    deliveredAllocateApplyOrder(AllocateApplyOrderDeliveredRequest.builder()
                            .allocateApplyOrderId(Long.valueOf(listResult.getResult().get(0).getAllocateApplyOrderId())).build());
                }
            }catch (Throwable e){
                log.error("cancel_DeliveredAllocateApplyOrder_error",e);
            }
            return response;
        }
        //循环获取到 不同交货单 的同一个调拨单的 子单 交货数量
        Map<String, List<AllocateOrderDeliveryScItemDTO>> map = Maps.newHashMap();
        List<AllocateOrderDeliveryScItemDTO> scItemDTOList = Lists.newArrayList();
        AllocateOrderDeliveryRequest freshRequest = new AllocateOrderDeliveryRequest();
        AllocateOrderLoadListRequest queryAllocateOrder = new AllocateOrderLoadListRequest();
        queryAllocateOrder.setOutAllocateOrderId(allocateOrderCancelDeliveredRequest.getOutAllocateOrderId());
        Result<List<AllocateOrder>> loadAllocateOrderList = allocateOrderService.loadAllocateOrderList(queryAllocateOrder);
        if (loadAllocateOrderList == null || CollectionUtils.isEmpty(loadAllocateOrderList.getResult())){
            return response;
        }
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(loadAllocateOrderList.getResult().get(0).getReceiveOrgId());

//        //可能出现多个调拨单 交货单唯一  交货单 算出 每个商品的交货数量
        log.info("cancelDelivered_exists_orders:{}",JSON.toJSONString(orderList));
        for (ConsignmentOrder order : orderList.getResult()) {
            ConsignmentOrderLineLoadListRequest lineLoadListRequest = new ConsignmentOrderLineLoadListRequest();
            lineLoadListRequest.setConsignmentOrderId(order.getId().toString());
            //查询出1000分页的交货明细
            lineLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<ConsignmentOrderLine>> listResult = consignmentOrderLineService.loadConsignmentOrderLineList(lineLoadListRequest);
            if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
                continue;
            }
            List<ConsignmentOrderLine> lineList;
            if (isECommerceOrder){
                lineList = listResult.getResult().stream().filter(x->StringUtils.isNotBlank(x.getOuterStoLineId())
                    && StringUtils.isNotBlank(x.getQty())).collect(Collectors.toList());
            }else {
                lineList =  listResult.getResult().stream()
                        .filter(x -> StringUtils.isNotBlank(x.getScItemId()) && StringUtils.isNotBlank(x.getQty()))
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(lineList)) {
                continue;
            }
            Map<String, List<ConsignmentOrderLine>> scItemMap;
            //电商调拨单 用外部行号
            if (isECommerceOrder){
                scItemMap = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getOuterStoLineId));

            }else {
                scItemMap = lineList.stream()
                        .collect(Collectors.groupingBy(ConsignmentOrderLine::getScItemId));
            }
            scItemMap.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    int sum = v.stream().map(ConsignmentOrderLine::getQty).filter(Objects::nonNull)
                            .map(String::trim).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                    // 物料 -> 交货累计数量
                    AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
                    if (isECommerceOrder){
                        scItemDTO.setOutAllocateOrderLineId(k);
                    }else {
                        scItemDTO.setScItemId(k);
                    }
                    scItemDTO.setDeliveryQuantity(sum + "");
                    scItemDTOList.add(scItemDTO);
                }
            });
        }
        log.info("cancelDelivered_scItemDTOList:{}",JSON.toJSONString(scItemDTOList));
        List<AllocateOrderDeliveryScItemDTO> freshScItemDTOList = Lists.newArrayList();
        //重新分组聚合 电商调拨单根据外部行号
        if (CollectionUtils.isNotEmpty(scItemDTOList)) {
            Map<String, List<AllocateOrderDeliveryScItemDTO>> collect;
            if (isECommerceOrder){
                collect = scItemDTOList.stream().collect(Collectors.groupingBy(AllocateOrderDeliveryScItemDTO::getOutAllocateOrderLineId));

            }else{
                collect = scItemDTOList.stream()
                        .collect(Collectors.groupingBy(AllocateOrderDeliveryScItemDTO::getScItemId));
            }
            collect.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    int sum = v.stream().map(AllocateOrderDeliveryScItemDTO::getDeliveryQuantity).filter(Objects::nonNull)
                            .map(String::trim).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                    AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
                    if (isECommerceOrder){
                        scItemDTO.setOutAllocateOrderLineId(k);
                    }else {
                        scItemDTO.setScItemId(k);
                    }

                    scItemDTO.setDeliveryQuantity(sum + "");
                    freshScItemDTOList.add(scItemDTO);
                }
            });
        }
        freshRequest.setDeliveryScItemDTOList(freshScItemDTOList);
        log.info("cancelDelivered_freshScItemDTOList:{}",JSON.toJSONString(freshScItemDTOList));
        //参数 找到了调拨单  调拨物料的集合
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setOutAllocateOrderId(outAllocateOrderId);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return response;
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        if (CollectionUtils.isEmpty(freshRequest.getDeliveryScItemDTOList())) {
            return response;
        }
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            return response;
        }
        for (AllocateOrderDetail detail : result.getResult()) {
            if (StringUtils.isBlank(detail.getScItemId())) {
                continue;
            }
            List<AllocateOrderDeliveryScItemDTO> scItemDTOS;
            //电商调拨单 外部行号
            if (isECommerceOrder){
                scItemDTOS = freshScItemDTOList.stream()
                        .filter(x->Objects.equals(x.getOutAllocateOrderLineId(),InfoUtil.deleteZeroPrefix(detail.getOutAllocateOrderLineId())))
                        .collect(Collectors.toList());
            }else{
                scItemDTOS = freshScItemDTOList.stream().filter(x -> Objects.equals(x.getScItemId(), detail.getScItemId()))
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(scItemDTOS)) {
//                detail.setDeliveryDate(null);
                detail.setDeliveryDate(new Date(0));
                detail.setDeliveryQuantity("");
            } else {
                AllocateOrderDeliveryScItemDTO scItemDTO = scItemDTOS.get(0);
//                detail.setDeliveryDate();
                detail.setDeliveryQuantity(scItemDTO.getDeliveryQuantity());
                detail.setDeliveryDate(new Date());
                detail.setGmt_modified(new Date());
            }
            detail.setShipTime(null);
            detail.setShipQuantity(null);
            detail.setReceiveTime(null);
            detail.setReceiveQuantity(null);
            allocateOrderDetailService.updateAllocateOrderDetail(detail);

        }
//        AllocateOrderWithOrderDetailsSDO sdo = allocateOrderReadRepository.get(allocateOrderRequest);
//        saveDocumentLog(oldSDO, sdo, Integer.parseInt(AllocateApplyOrderOperationTypeEnum.CANCELRECEIVED.getValue()),
//                OperatorType.INNER_INTERFACE.getOperatorType());
        response.setDeliveryOrderId(allocateOrderCancelDeliveredRequest.getDeliveryOrderId());
        try{
            if (StringUtils.isNotBlank(allocateOrder.getAllocateApplyOrderId())){
                deliveredAllocateApplyOrder(AllocateApplyOrderDeliveredRequest.builder()
                        .allocateApplyOrderId(Long.valueOf(allocateOrder.getAllocateApplyOrderId())).build());
            }
        }catch (Throwable e){
            log.error("cancel_DeliveredAllocateApplyOrder_error",e);
        }

        return response;
    }

    /**
     * 交货 从交货单里取出值更新
     *
     * @param allocateOrderDeliveryRequest
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderDeliveryResponse delivered(AllocateOrderDeliveryRequest allocateOrderDeliveryRequest) {
        if (true) {
            return deliveredFresh(allocateOrderDeliveryRequest);
        }

        AllocateOrderDeliveryResponse response = new AllocateOrderDeliveryResponse();
        if (StringUtils.isBlank(allocateOrderDeliveryRequest.getCode())
                && StringUtils.isBlank(allocateOrderDeliveryRequest.getOutAllocateOrderId())) {
            return response;
        }
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        if (StringUtils.isNotBlank(allocateOrderDeliveryRequest.getCode())) {
            allocateOrderLoadListRequest.setCode(allocateOrderDeliveryRequest.getCode());
        } else if (StringUtils.isNotBlank(allocateOrderDeliveryRequest.getOutAllocateOrderId())) {
            allocateOrderLoadListRequest.setOutAllocateOrderId(allocateOrderDeliveryRequest.getOutAllocateOrderId());
        }
        allocateOrderLoadListRequest.setSize(1000);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return response;
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        if (CollectionUtils.isEmpty(allocateOrderDeliveryRequest.getDeliveryScItemDTOList())) {
            return response;
        }
        List<String> scItemCodes = allocateOrderDeliveryRequest.getDeliveryScItemDTOList()
                .stream().filter(Objects::nonNull).filter(x -> StringUtils.isNotBlank(x.getScItemCode()))
                .map(AllocateOrderDeliveryScItemDTO::getScItemCode).distinct().collect(Collectors.toList());
        Map<String, AllocateOrderDetailBatchGetScItemResponse> map = InfoUtil.getScItemMapByOutCodes(scItemCodes);

        Date deliveryDate = new Date();
        if (StringUtils.isNotBlank(allocateOrderDeliveryRequest.getDeliveryDate())) {
            deliveryDate = TimeUtil.parseSimpleDateFormat(allocateOrderDeliveryRequest.getDeliveryDate());
        }
        for (AllocateOrderDeliveryScItemDTO scItemDTO : allocateOrderDeliveryRequest.getDeliveryScItemDTOList()) {
            AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
            AllocateOrderDetailBatchGetScItemResponse scItemResponse = map.get(scItemDTO.getScItemCode());
            if (scItemResponse == null || StringUtils.isBlank(scItemResponse.getScItemId())) {
                continue;
            }
            detailLoadListRequest.setScItemId(scItemResponse.getScItemId());
            detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
            if (result == null || CollectionUtils.isEmpty(result.getResult())) {
                continue;
            }
            AllocateOrderDetail allocateOrderDetail = result.getResult().get(0);
            allocateOrderDetail.setDeliveryQuantity(InfoUtil.addNoPoint(allocateOrderDetail.getDeliveryQuantity(),
                    scItemDTO.getDeliveryQuantity()));
            allocateOrderDetail.setDeliveryDate(deliveryDate);
            allocateOrderDetail.setGmt_modified(new Date());
            allocateOrderDetailService.updateAllocateOrderDetail(allocateOrderDetail);
        }
        response.setCode(allocateOrder.getCode());
        response.setId(allocateOrder.getId().toString());
        return response;
    }

    public static Long getPrice(String price) {
        if (StringUtils.isBlank(price)) {
            return null;
        }
        BigDecimal v = new BigDecimal(price).movePointRight(2);
        return v.longValue();
    }


    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderCancelResponse cancel(AllocateOrderCancelRequest allocateOrderCancelRequest) {
        if (allocateOrderCancelRequest == null || StringUtils.isBlank(allocateOrderCancelRequest.getCode())) {
            throw new FacadeException("OTS-03-005-00-15-001");
        }
        AllocateOrderLoadListRequest request = new AllocateOrderLoadListRequest();
        request.setCode(allocateOrderCancelRequest.getCode());
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(request);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-002");
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        allocateOrder.setStatus(AllocateOrderStatus.Cancel.getValue());
        allocateOrder.setGmt_modified(new Date());
        allocateOrder.setUpdater(allocateOrderCancelRequest.getUpdater());
        allocateOrderService.updateAllocateOrder(allocateOrder);

        AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
        listRequest.setAllocateOrderId(allocateOrder.getId());
        listRequest.setLimit(500);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
            for (AllocateOrderDetail detail : result.getResult()) {
                detail.setStatus(AllocateOrderStatus.Cancel.getValue());
                detail.setGmt_modified(new Date());
                allocateOrderDetailService.updateAllocateOrderDetail(detail);
            }
        }
        AllocateOrderCancelResponse response = new AllocateOrderCancelResponse();
        response.setCode(allocateOrder.getCode());
        response.setAllocateOrderId(allocateOrder.getId().toString());
        return response;
    }

    @RepositoryInvoker(printLog = true)
    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    /**
     * sap 回调
     */
    public AllocateOrderNotifyResponse notify(AllocateOrderNotifyRequest allocateOrderNotifyRequest) {
        if (allocateOrderNotifyRequest == null) {
            throw new FacadeException("OTS-03-005-00-15-011");
        }
        if (StringUtils.isBlank(allocateOrderNotifyRequest.getInnerKey())) {
            throw new FacadeException("OTS-03-005-00-15-013");
        }
        if (allocateOrderNotifyRequest.getSuccess() == null) {
            throw new FacadeException("OTS-03-005-00-15-014");
        }
        String code = allocateOrderNotifyRequest.getInnerKey();
        AllocateOrderLoadListRequest request = new AllocateOrderLoadListRequest();
        request.setCode(code);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(request);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            throw new FacadeException("OTS-03-005-00-15-067");
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        if (Objects.equals(allocateOrderNotifyRequest.getSuccess(), Boolean.TRUE)) {
            if (StringUtils.isBlank(allocateOrderNotifyRequest.getOuterKey())) {
                throw new FacadeException("OTS-03-005-00-15-015");
            }
            allocateOrder.setOutAllocateOrderId(allocateOrderNotifyRequest.getOuterKey());
            //如果是待推送状态,就改成待发货
            if (AllocateOrderStatus.WAIT_PUSH.getValue().equals(allocateOrder.getStatus())){
                allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            }
//            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            allocateOrder.setGmt_modified(new Date());
            allocateOrderService.updateAllocateOrder(allocateOrder);
            AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
            detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                for (AllocateOrderDetail detail : result.getResult()) {
                    //如果是待推送状态,就修改一下
                    if (AllocateOrderStatus.WAIT_PUSH.getValue().equals(detail.getStatus())){
                        detail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        detail.setGmt_modified(new Date());
                        allocateOrderDetailService.updateAllocateOrderDetail(detail);
                    }
                }
            }
        } else {
            if (StringUtils.isBlank(allocateOrderNotifyRequest.getMessage())) {
                throw new FacadeException("OTS-03-005-00-15-016");
            }
            allocateOrder.setMessage(allocateOrderNotifyRequest.getMessage());
            allocateOrder.setGmt_modified(new Date());
            allocateOrderService.updateAllocateOrder(allocateOrder);
        }
        AllocateOrderNotifyResponse response = new AllocateOrderNotifyResponse();
        response.setSuccess(allocateOrderNotifyRequest.getSuccess());
        response.setInnerKey(allocateOrderNotifyRequest.getInnerKey());
        response.setOuterKey(allocateOrderNotifyRequest.getOuterKey());
        response.setMessage(allocateOrderNotifyRequest.getMessage());
        return response;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public AllocateOrderCancelReceivedResponse cancelReceived(AllocateOrderCancelReceivedRequest request) {
        AllocateOrderCancelReceivedResponse response = new AllocateOrderCancelReceivedResponse();
        if (request == null || StringUtils.isBlank(request.getId())
                || CollectionUtils.isEmpty(request.getReceivedScItemDTOS())) {
            throw new FacadeException("OTS-03-005-00-15-071");
        }
        if (StringUtils.isBlank(request.getOutMaterialCertificateId())) {
            throw new FacadeException("OTS-03-005-00-15-076");
        }
        List<AllocateOrderReceivedScItemDTO> receiveScItems = request.getReceivedScItemDTOS().stream()
                .filter(x -> StringUtils.isNotBlank(x.getReceiveQuantity()) && StringUtils.isNotBlank(x.getScItemId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(receiveScItems)) {
            throw new FacadeException("OTS-03-005-00-15-053");
        }
        boolean illegal = receiveScItems.stream().anyMatch(x -> InfoUtil.getInt(x.getReceiveQuantity()) <= 0);
        if (illegal) {
            throw new FacadeException("OTS-03-005-00-15-054");
        }
        LoadAllocateOrderRequest loadAllocateOrderRequest = new LoadAllocateOrderRequest();
        loadAllocateOrderRequest.setId(request.getId());
        AllocateOrder allocateOrder = allocateOrderService.loadAllocateOrder(loadAllocateOrderRequest);
        if (allocateOrder == null) {
            throw new FacadeException("OTS-03-005-00-15-068");
        }
        boolean checkOut = InfoUtil.checkContain(allocateOrder.getCancelReceiveOutMaterialCertificateId(),
                request.getOutMaterialCertificateId());
        if (checkOut) {
            log.error("调拨单撤销收货请求重复:{}", JSON.toJSONString(request));
            return response;
        }
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(allocateOrder.getReceiveOrgId());
        //聚合相同scItemId的数量
        handleReceivedScItemData(receiveScItems,isECommerceOrder);
        /**
         * 把收货状态 进行回退  部分收货  已发货  -> 部分收货  -> 已发货 -> 部分发货 -> 待发货
         */
//        Set<Integer> status = Sets.newHashSet();
        for (AllocateOrderReceivedScItemDTO receiveScItem : receiveScItems) {
            AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
            listRequest.setAllocateOrderId(Long.valueOf(request.getId()));
            if (isECommerceOrder){
                listRequest.setOutAllocateOrderLineId(receiveScItem.getOutAllocateOrderLineId());
            }else {
                listRequest.setScItemId(receiveScItem.getScItemId());
            }
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
            log.info("AllocateOrderWriteRepositoryImpl.cancelReceived.getDetailResult,request:{},res:{}",
                    JSON.toJSONString(listRequest),JSON.toJSONString(result));
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                AllocateOrderDetail orderDetail = result.getResult().get(0);
                if (orderDetail.getReceiveQuantity() == null) {
                    orderDetail.setReceiveQuantity(0);
                }
                Integer quantity = InfoUtil.getInt(orderDetail.getQuantity());
                Integer receiveQuantity = orderDetail.getReceiveQuantity();
                Integer cancel = InfoUtil.getInt(receiveScItem.getReceiveQuantity());
                Integer sum = receiveQuantity - cancel;
                orderDetail.setReceiveQuantity(sum);

                //已关闭 收发货不影响状态
                if (!Objects.equals(orderDetail.getStatus(),AllocateOrderStatus.CLOSED.getValue())){
                    //仍有收货数量 设置为部分收货
                    if (sum > 0 && sum < quantity) {
                        orderDetail.setStatus(AllocateOrderStatus.Part_Received.getValue());
                    } else if (sum >= quantity) {
                        //收货超出 仍为已收货
                        orderDetail.setStatus(AllocateOrderStatus.Received.getValue());
                    } else {
                        //收货时间置为空 -> 默认时间 查询时处理
                        orderDetail.setReceiveTime(new Date(0));
                        Integer shipQuantity = orderDetail.getShipQuantity() == null ? 0 : orderDetail.getShipQuantity();
                        //不再是收货的时候, 去找发货状态
                        if (shipQuantity >= quantity) {
                            orderDetail.setStatus(AllocateOrderStatus.Shipped.getValue());
                        } else if (shipQuantity > 0) {
                            orderDetail.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                        } else {
                            orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        }
                    }

                }

                //防止004的其他影响
                orderDetail.setShipQuantity(null);
                orderDetail.setShipTime(null);
                orderDetail.setDeliveryDate(null);
                orderDetail.setDeliveryQuantity(null);
                log.info("AllocateOrderWriteRepositoryImpl.cancelReceived.updateAllocateOrderDetail,{}",JSON.toJSONString(orderDetail));
                allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
            }else {
                throw new FacadeException("OTS-03-005-00-15-106");
            }
        }
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(500);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        //子单都更新完了
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())
            && !Objects.equals(allocateOrder.getStatus(),AllocateOrderStatus.CLOSED.getValue())) {
//            && CollectionUtils.isNotEmpty(status)){
            //找出非关闭的子单状态集合
            List<Integer> statusList = result.getResult().stream()
                    .filter(x -> !Objects.equals(x.getClose(), Boolean.TRUE))
                    .map(AllocateOrderDetail::getStatus).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(statusList)) {
                //如果都是收货 收货
                boolean received = statusList.stream().allMatch(x -> AllocateOrderStatus.Received.getValue().equals(x));
                if (received) {
                    allocateOrder.setStatus(AllocateOrderStatus.Received.getValue());
                } else {
                    //如果有部分收货 部分收货
                    boolean partReceived = statusList.stream()
                            .anyMatch(x -> AllocateOrderStatus.Part_Received.getValue().equals(x)
                                    || AllocateOrderStatus.Received.getValue().equals(x));
                    if (partReceived) {
                        allocateOrder.setStatus(AllocateOrderStatus.Part_Received.getValue());
                    } else {
                        //已发货
                        boolean shipped = statusList.stream().allMatch(x -> AllocateOrderStatus.Shipped.getValue().equals(x));
                        if (shipped) {
                            allocateOrder.setStatus(AllocateOrderStatus.Shipped.getValue());
                        } else {
                            //部分发货
                            boolean partShipped = statusList.stream()
                                    .anyMatch(x -> AllocateOrderStatus.Part_Shipped.getValue().equals(x)
                                            || AllocateOrderStatus.Shipped.getValue().equals(x));
                            if (partShipped) {
                                allocateOrder.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                            } else {
                                allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                            }
                        }
                    }
                }
                allocateOrder.setGmt_modified(new Date());
            }
            allocateOrder.setCancelReceiveOutMaterialCertificateId(
                    InfoUtil.splice(allocateOrder.getCancelReceiveOutMaterialCertificateId(),
                            request.getOutMaterialCertificateId()));
            allocateOrderService.updateAllocateOrder(allocateOrder);
        }
        response.setCode(allocateOrder.getCode());
        return response;
    }

    @Override
    public boolean updata(AllocateOrderSDO allocateOrderSDO) {
        if (Objects.nonNull(allocateOrderSDO)) {
            AllocateOrder allocateOrder = JsonUtil.convert(allocateOrderSDO, AllocateOrder.class);
            allocateOrderService.updateAllocateOrder(allocateOrder);
        }
        return true;
    }

    /**
     * @param old
     * @param fresh
     */
    private void saveDocumentLog(AllocateOrderWithOrderDetailsSDO old,
                                 AllocateOrderWithOrderDetailsSDO fresh,
                                 Integer operateType,
                                 Integer operatorType) {
        try {

            LoginUser loginUser = epochLoginUserService.getLoginUser();
            //因为日志表的长度限制, 现在日志没有用到子单明细,就把子单给缩略掉
            if (old != null){
                old.setAllocateOrderDetailSDOS(Lists.newArrayList());
            }
            if (fresh != null){
                fresh.setAllocateOrderDetailSDOS(Lists.newArrayList());
            }
            OpLogModel<AllocateOrderWithOrderDetailsSDO> opLogModel = OpLogModel.<AllocateOrderWithOrderDetailsSDO>builder()
                    .oldValue(old)
                    .newValue(fresh)
                    .moduleName(ModuleEnum.UNIFIED_INVENTORY.getModuleName())
                    .moduleId(ModuleEnum.UNIFIED_INVENTORY.getModuleId())
                    .operateType(operateType)
                    .operatorType(Optional.ofNullable(operatorType).orElse(OperatorType.USER.getOperatorType()))
                    .operatorId(loginUser.getEmpId())
                    .objectId(fresh.getAllocateOrderSDO().getId().toString())
                    .objectName(fresh.getAllocateOrderSDO().getCode())
                    .build();
            log.asyncMonitorObjectChangeV2(opLogModel);
        } catch (Exception e) {
            log.error("调拨单日志写入失败:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 确认日期改为sap传什么时间我们存什么时间
     *
     * @param detail
     * @param dto
     */
    public static void handleConfirmTime(AllocateOrderDetail detail, AllocateOrderScItemDetailDTO dto) {
        if (detail == null || dto == null) {
            return;
        }
        //2022.02.22变更 确认日期改为sap传什么时间我们存什么时间
        //2022.02.26变更 sap如果不传递 就置为特殊值.
        if (dto.getConfirmTime() != null){
            detail.setConfirmTime(dto.getConfirmTime());
        }else {
            //如果库里查询的是不是空值就设置为特殊数据 前端页面有特殊显示处理
            if (detail.getConfirmTime() != null){
                detail.setConfirmTime(new Date(0));
            }
        }
//        Integer confirmQuantity = InfoUtil.getInt(dto.getConfirmQuantity());
//        if (confirmQuantity > 0) {
//            detail.setConfirmTime(new Date());
//        } else {
//            detail.setConfirmTime(new Date(0));
//        }
    }

    /**
     * 调拨单更新时判断下行状态、单据状态是否更新
     * <p>
     * 行状态：收货数量不为空，数量<=收货数量 已收货
     * <p>
     * 数量>收货数量  部分收货
     * 收货数量为空，发货数量不为空 ，根据发货数量和数量关系判断状态
     * <p>
     * 收货、发货数量都为空，待发货
     *
     * @param detail
     */
    public void sapUpdateLineStatus(AllocateOrderDetail detail) {
        if (detail == null) {
            return;
        }
        Integer shipQuantity = detail.getShipQuantity() == null ? 0 : detail.getShipQuantity();
        Integer receiveQuantity = detail.getReceiveQuantity() == null ? 0 : detail.getReceiveQuantity();
        Integer quantity = InfoUtil.getInt(detail.getQuantity());
        //如果是关闭 取消 待推送 状态 就不进行判断收发货的状态了.
        if (Objects.equals(detail.getStatus(), AllocateOrderStatus.CLOSED.getValue()) ||
                Objects.equals(detail.getStatus(), AllocateOrderStatus.Cancel.getValue()) ||
                Objects.equals(detail.getStatus(), AllocateOrderStatus.WAIT_PUSH.getValue()) ||
                Objects.equals(detail.getStatus(), AllocateOrderStatus.DRAFT.getValue())) {
            return;
        }
        //考虑到冲销  没有负收货负发货  判断量都大于0的
        if (receiveQuantity > 0) {
            if (quantity <= receiveQuantity) {
                detail.setStatus(AllocateOrderStatus.Received.getValue());
            } else {
                detail.setStatus(AllocateOrderStatus.Part_Received.getValue());
            }
        } else if (shipQuantity > 0) {
            if (quantity <= shipQuantity) {
                detail.setStatus(AllocateOrderStatus.Shipped.getValue());
            } else {
                detail.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
            }
        }

    }

    /**
     * 这个额外用来判断收货发货的
     */
    public void sapUpdateOrderStatus(Result<List<AllocateOrderDetail>> detailResult, AllocateOrder allocateOrder) {
        if (allocateOrder == null || detailResult == null || CollectionUtils.isEmpty(detailResult.getResult())) {
            return;
        }
        List<AllocateOrderDetail> list = detailResult.getResult();
        List<Integer> statusList = list.stream()
                .filter(x -> !Objects.equals(x.getStatus(), AllocateOrderStatus.CLOSED.getValue())
                        && !Objects.equals(x.getStatus(), AllocateOrderStatus.Cancel.getValue())
                        && !Objects.equals(x.getStatus(), AllocateOrderStatus.WAIT_PUSH.getValue())
                        && !Objects.equals(x.getStatus(), AllocateOrderStatus.DRAFT.getValue()))
                .map(AllocateOrderDetail::getStatus).collect(Collectors.toList());
//        list = list.stream().filter(x-> !Objects.equals(x.getStatus(),AllocateOrderStatus.CLOSED)
//            && !Objects.equals(x.getStatus(),AllocateOrderStatus.Cancel)
//            && !Objects.equals(x.getStatus(),AllocateOrderStatus.WAIT_PUSH)
//                && !Objects.equals(x.getStatus(),AllocateOrderStatus.DRAFT))
//                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(statusList)) {
            return;
        }
        //如果都是收货 收货
        boolean received = statusList.stream().allMatch(x -> AllocateOrderStatus.Received.getValue().equals(x));
        if (received) {
            allocateOrder.setStatus(AllocateOrderStatus.Received.getValue());
        } else {
            //如果有部分收货 部分收货
            boolean partReceived = statusList.stream()
                    .anyMatch(x -> AllocateOrderStatus.Part_Received.getValue().equals(x)
                            || AllocateOrderStatus.Received.getValue().equals(x));
            if (partReceived) {
                allocateOrder.setStatus(AllocateOrderStatus.Part_Received.getValue());
            } else {
                //已发货
                boolean shipped = statusList.stream().allMatch(x -> AllocateOrderStatus.Shipped.getValue().equals(x));
                if (shipped) {
                    allocateOrder.setStatus(AllocateOrderStatus.Shipped.getValue());
                } else {
                    //部分发货
                    boolean partShipped = statusList.stream()
                            .anyMatch(x -> AllocateOrderStatus.Part_Shipped.getValue().equals(x)
                                    || AllocateOrderStatus.Shipped.getValue().equals(x));
                    if (partShipped) {
                        allocateOrder.setStatus(AllocateOrderStatus.Part_Shipped.getValue());
                    } else {
                        allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                    }
                }
            }
        }
        allocateOrder.setGmt_modified(new Date());
        allocateOrderService.updateAllocateOrder(allocateOrder);
    }

    //更新调拨单里预报单行号的问题
    public void updateAllocateApplyOrderLineId(String code, Long allocateApplyOrderId) {
        if (StringUtils.isBlank(code) || allocateApplyOrderId == null) {
            return;
        }
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
//        detailLoadListRequest.setAllocateOrderId(allocateOrderId.toString());
        detailLoadListRequest.setAllocateOrderCode(code);
        detailLoadListRequest.setLimit(1000);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            return;
        }
        //获取预报单明细
        AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest = new AllocateApplyOrderDetailLoadListRequest();
        allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(allocateApplyOrderId.intValue());
        allocateApplyOrderDetailLoadListRequest.setLimit(1000);
        Result<List<AllocateApplyOrderDetail>> listResult = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return;
        }
        //找到 并更新行号
        for (AllocateOrderDetail detail : result.getResult()) {
            List<AllocateApplyOrderDetail> collect = listResult.getResult().stream().filter(x -> Objects.equals(x.getGoodsId(), detail.getScItemId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                AllocateApplyOrderDetail allocateApplyOrderDetail = collect.get(0);
                detail.setAllocateApplyOrderLineId(allocateApplyOrderDetail.getLineNo() == null ? null : allocateApplyOrderDetail.getLineNo().toString());
                detail.setGmt_modified(new Date());
                allocateOrderDetailService.updateAllocateOrderDetail(detail);
            }
        }

    }

    /**
     * 一个需要把库里的收货量 发货量  写入时 *1000 读取时除以 1000
     * 把相同货品id的数量聚合一下
     */
    public void handleShippedScItemData(List<AllocateOrderShippedScItemDTO> shipScItems,boolean isECommerceOrder){
        //理论上到这一步不会是空字符串
        if (CollectionUtils.isEmpty(shipScItems)){
            return;
        }
        List<AllocateOrderShippedScItemDTO> data = Lists.newArrayList();
        Map<String, List<AllocateOrderShippedScItemDTO>> map;
        //电商调拨单 根据外部行号分组
        if (isECommerceOrder){
            map = shipScItems.stream().collect(Collectors.groupingBy(AllocateOrderShippedScItemDTO::getOutAllocateOrderLineId));
        }else {
            map = shipScItems.stream()
                    .collect(Collectors.groupingBy(AllocateOrderShippedScItemDTO::getScItemId));
        }
        for (Map.Entry<String, List<AllocateOrderShippedScItemDTO>> entry : map.entrySet()) {
            AllocateOrderShippedScItemDTO scItemDTO = new AllocateOrderShippedScItemDTO();
            if (isECommerceOrder){
                scItemDTO.setOutAllocateOrderLineId(entry.getKey());
            }else {
                scItemDTO.setScItemId(entry.getKey());
            }
            //获取到放大1000倍的数量
            Integer sum = entry.getValue().stream().map(AllocateOrderShippedScItemDTO::getShipQuantity)
                    .map(x->{
                        Integer quantity = InfoUtil.getInt(x);
                        return quantity;
                    }).mapToInt(Integer::intValue).sum();
//                    .map(x -> {
//                        BigDecimal bigDecimal = new BigDecimal(x).movePointRight(3);
//                        return bigDecimal;
//                    }).mapToInt(BigDecimal::intValue).sum();
            scItemDTO.setShipQuantity(sum.toString());
            data.add(scItemDTO);
        }
        //重新赋值下
        shipScItems.clear();
        shipScItems.addAll(data);
    }

    /**
     * 一个需要把库里的收货量 发货量  写入时 *1000 读取时除以 1000
     * 把相同货品id的数量聚合一下
     */
    public void handleReceivedScItemData(List<AllocateOrderReceivedScItemDTO> receiveScItems,boolean isECommerceOrder){
        //理论上到这一步不会是空字符串
        if (CollectionUtils.isEmpty(receiveScItems)){
            return;
        }
        List<AllocateOrderReceivedScItemDTO> data = Lists.newArrayList();
        Map<String, List<AllocateOrderReceivedScItemDTO>> map;
        if (isECommerceOrder){
            map = receiveScItems.stream().collect(Collectors.groupingBy(AllocateOrderReceivedScItemDTO::getOutAllocateOrderLineId));
        }else{
            map = receiveScItems.stream()
                    .collect(Collectors.groupingBy(AllocateOrderReceivedScItemDTO::getScItemId));
        }
        for (Map.Entry<String, List<AllocateOrderReceivedScItemDTO>> entry : map.entrySet()) {
            AllocateOrderReceivedScItemDTO scItemDTO = new AllocateOrderReceivedScItemDTO();
            if (isECommerceOrder){
                scItemDTO.setOutAllocateOrderLineId(entry.getKey());
            }else {
                scItemDTO.setScItemId(entry.getKey());
            }
            //获取到放大1000倍的数量
            Integer sum = entry.getValue().stream().map(AllocateOrderReceivedScItemDTO::getReceiveQuantity)
                    .map(x->{
                        Integer quantity = InfoUtil.getInt(x);
                        return quantity;
                    }).mapToInt(Integer::intValue).sum();
//                    .map(x -> {
//                        BigDecimal bigDecimal = new BigDecimal(x).movePointRight(3);
//                        return bigDecimal;
//                    }).mapToInt(BigDecimal::intValue).sum();
            scItemDTO.setReceiveQuantity(sum.toString());
            data.add(scItemDTO);
        }
        //重新赋值下
        receiveScItems.clear();
        receiveScItems.addAll(data);
    }

    /**
     * 一个需要把库里的撤销收货量 发货量  写入时 *1000 读取时除以 1000
     * 把相同货品id的数量聚合一下
     */
    public void handleCancelShippedScItemData(List<AllocateOrderCancelShippedScItemDTO> shipScItems, boolean isECommerceOrder){
        //理论上到这一步不会是空字符串
        if (CollectionUtils.isEmpty(shipScItems)){
            return;
        }
        List<AllocateOrderCancelShippedScItemDTO> data = Lists.newArrayList();
        Map<String, List<AllocateOrderCancelShippedScItemDTO>> map;
        if (isECommerceOrder){
            map = shipScItems.stream().collect(Collectors.groupingBy(AllocateOrderCancelShippedScItemDTO::getOutAllocateOrderLineId));
        }else{
            map = shipScItems.stream()
                    .collect(Collectors.groupingBy(AllocateOrderCancelShippedScItemDTO::getScItemId));
        }
        for (Map.Entry<String, List<AllocateOrderCancelShippedScItemDTO>> entry : map.entrySet()) {
            AllocateOrderCancelShippedScItemDTO scItemDTO = new AllocateOrderCancelShippedScItemDTO();
            if (isECommerceOrder){
                scItemDTO.setOutAllocateOrderLineId(entry.getKey());
            }else {
                scItemDTO.setScItemId(entry.getKey());
            }
            //获取到放大1000倍的数量
            Integer sum = entry.getValue().stream().map(AllocateOrderCancelShippedScItemDTO::getShipQuantity)
                    .map(x->{
                        Integer quantity = InfoUtil.getInt(x);
                        return quantity;
                    }).mapToInt(Integer::intValue).sum();
//                    .map(x -> {
//                        BigDecimal bigDecimal = new BigDecimal(x).movePointRight(3);
//                        return bigDecimal;
//                    }).mapToInt(BigDecimal::intValue).sum();
            scItemDTO.setShipQuantity(sum.toString());
            data.add(scItemDTO);
        }
        //重新赋值下
        shipScItems.clear();
        shipScItems.addAll(data);
    }


    OrganizationSDO getOrgSDO(String orgId){
        if (org.apache.commons.lang.StringUtils.isBlank(orgId)){
            return null;
        }
//        GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//        getOrganiztionByIdRequest.setId(orgId);
//        OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
        BaselineGetOrganizationById2Request request = new BaselineGetOrganizationById2Request();
        request.setId(orgId);
        Result<com.epoch.app.bcorder.model.dto.OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(request);
        if (organizationSDOResult != null){
            return organizationSDOResult.getResult();
        }
        return null;
    }


    /**
     * 017接口先于008 013接口过来 需要修正交货数量
     * @param outAllocateOrderId
     */
    public void delivery(String outAllocateOrderId){
        if (StringUtils.isBlank(outAllocateOrderId)){
//            log.error("AllocateOrderWriteServiceImpl_delivery");
            return;
        }
        ConsignmentOrderLoadListRequest consignmentOrderLoadListRequest = new ConsignmentOrderLoadListRequest();
        //交货单查询的时候要去0 因为库里的存的是不带0的
        consignmentOrderLoadListRequest.setOuterStoOrderId(InfoUtil.deleteZeroPrefix(outAllocateOrderId));
        consignmentOrderLoadListRequest.setStatus(1);
        consignmentOrderLoadListRequest.setLimit(MAX_PAGE_SIZE);
        //交货单
        Result<List<ConsignmentOrder>> loadConsignmentOrderList = consignmentOrderService.loadConsignmentOrderList(consignmentOrderLoadListRequest);
        if (loadConsignmentOrderList == null || CollectionUtils.isEmpty(loadConsignmentOrderList.getResult())){
            return;
        }
        //交货明细
        List<ConsignmentOrderLine> lineList = Lists.newArrayList();
        //物料或者外部行号的交货日期
        Map<String,Date> dates = Maps.newHashMap();
        for (ConsignmentOrder consignmentOrder : loadConsignmentOrderList.getResult()) {
            ConsignmentOrderLineLoadListRequest consignmentOrderLineLoadListRequest = new ConsignmentOrderLineLoadListRequest();
            consignmentOrderLineLoadListRequest.setConsignmentOrderId(consignmentOrder.getId().toString());
            consignmentOrderLineLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<ConsignmentOrderLine>> consignmentOrderLineList = consignmentOrderLineService.loadConsignmentOrderLineList(consignmentOrderLineLoadListRequest);
            if (consignmentOrderLineList == null || CollectionUtils.isEmpty(consignmentOrderLineList.getResult())){
                continue;
            }
            lineList.addAll(consignmentOrderLineList.getResult());
        }
        //如果一条交货明细都没有,认为是删除由018处理
        if (CollectionUtils.isEmpty(lineList)){
            return;
        }
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setOutAllocateOrderId(outAllocateOrderId);
        Result<List<AllocateOrder>> loadAllocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (loadAllocateOrderList == null || CollectionUtils.isEmpty(loadAllocateOrderList.getResult())){
            return;
        }

        //判断是否是电商的调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(loadAllocateOrderList.getResult().get(0).getReceiveOrgId());
        //按照物料或者外部调拨单行号 聚合明细
        Map<String, List<ConsignmentOrderLine>> collect;
        //物料id/外部调拨单行号  -- 交货数量
        Map<String,String> dataMap = Maps.newHashMap();

        if (isECommerceOrder){
            collect = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getOuterStoLineId));
        }else {
            collect = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getScItemId));
        }
        //计算数量
        collect.forEach((k,v)->{
            if (CollectionUtils.isNotEmpty(v)){
                int sum = v.stream().map(ConsignmentOrderLine::getQty).filter(Objects::nonNull)
                        .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                dataMap.put(k,Integer.toString(sum));
                //找到最新的交货日期
                ConsignmentOrder consignmentOrder = loadConsignmentOrderList.getResult().stream().filter(x -> v.stream().
                                anyMatch(y -> Objects.equals(y.getConsignmentOrderId(), x.getId().toString())))
                        .sorted(Comparator.comparing(ConsignmentOrder::getGmt_create).reversed()).findFirst().orElse(null);
                if (consignmentOrder != null){
                    dates.put(k,consignmentOrder.getGmt_create());
                }
            }
        });
        //修改调拨单交货数量
        //查询调拨单明细
        AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        allocateOrderDetailLoadListRequest.setAllocateOrderId(loadAllocateOrderList.getResult().get(0).getId());
        allocateOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return;
        }
        //循环调拨单明细 匹配交货明细的修改数量 不匹配的清零数量
        for (AllocateOrderDetail detail : result.getResult()) {
            AllocateOrderDetail allocateOrderDetail = new AllocateOrderDetail();
            allocateOrderDetail.setId(detail.getId());
            if (isECommerceOrder){
                //电商调拨单用外部行号匹配
               if (dataMap.containsKey(detail.getOutAllocateOrderLineId())){
                   allocateOrderDetail.setDeliveryQuantity(dataMap.get(detail.getOutAllocateOrderLineId()));
                   //设置交货时间
                   if (dates.get(detail.getOutAllocateOrderLineId()) != null){
                       allocateOrderDetail.setDeliveryDate(dates.get(detail.getOutAllocateOrderLineId()));
                   }
               }else {
                   allocateOrderDetail.setDeliveryDate(new Date(0));
                   allocateOrderDetail.setDeliveryQuantity(Integer.toString(0));
               }
            }else {
                if (dataMap.containsKey(detail.getScItemId())){
                    allocateOrderDetail.setDeliveryQuantity(dataMap.get(detail.getScItemId()));
                    if (dates.get(detail.getScItemId()) != null){
                        allocateOrderDetail.setDeliveryDate(dates.get(detail.getScItemId()));
                    }
                }else {
                    allocateOrderDetail.setDeliveryDate(new Date(0));
                    allocateOrderDetail.setDeliveryQuantity(Integer.toString(0));
                }
            }
            allocateOrderDetailService.updateAllocateOrderDetail(allocateOrderDetail);
        }

    }

    //修正调拨单和明细状态
    @Override
    public boolean fixStatus(String outAllocateOrderId) {
        boolean res = false;
        if (StringUtils.isBlank(outAllocateOrderId)){
            return false;
        }
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setOutAllocateOrderId(outAllocateOrderId);
        Result<List<AllocateOrder>> loadAllocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (Objects.isNull(loadAllocateOrderList) || CollectionUtils.isEmpty(loadAllocateOrderList.getResult())){
            return false;
        }
        AllocateOrder allocateOrder = loadAllocateOrderList.getResult().get(0);
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        if (Objects.isNull(result) || CollectionUtils.isEmpty(result.getResult())){
            return false;
        }
        for (AllocateOrderDetail detail : result.getResult()) {
            sapUpdateLineStatus(detail);
            allocateOrderDetailService.updateAllocateOrderDetail(detail);
        }
        Result<List<AllocateOrderDetail>> listResult = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        sapUpdateOrderStatus(listResult,allocateOrder);
        return true;
    }

    @Override
    public boolean fixDeliveryQuantity(String outAllocateOrderId) {
        if (StringUtils.isBlank(outAllocateOrderId)){
            return false;
        }
        //找出触发更新操作的交货单 -> 此次对应的调拨单 -> 找到所有的调拨单 依据 调拨单号来找好了
        ConsignmentOrderLoadListRequest orderLoadListRequest = new ConsignmentOrderLoadListRequest();
        orderLoadListRequest.setOuterStoOrderId(InfoUtil.deleteZeroPrefix(outAllocateOrderId));
        //未删除
        orderLoadListRequest.setStatus(1);
        //还有个调拨单号
        orderLoadListRequest.setLimit(1000);
        Result<List<ConsignmentOrder>> orderList = consignmentOrderService.loadConsignmentOrderList(orderLoadListRequest);
        if (orderList == null || CollectionUtils.isEmpty(orderList.getResult())) {
            return false;
        }
        //循环获取到 不同交货单 的同一个调拨单的 子单 交货数量
        List<AllocateOrderDeliveryScItemDTO> scItemDTOList = Lists.newArrayList();

        //查询调拨单 判断是否是电商的
        AllocateOrderLoadListRequest queryAllocateOrderRequest = new AllocateOrderLoadListRequest();
        queryAllocateOrderRequest.setOutAllocateOrderId(outAllocateOrderId);
        Result<List<AllocateOrder>> loadAllocateOrderList = allocateOrderService.loadAllocateOrderList(queryAllocateOrderRequest);
        if (loadAllocateOrderList == null || CollectionUtils.isEmpty(loadAllocateOrderList.getResult())){
            return false;
        }
        //是否电商调拨单
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(loadAllocateOrderList.getResult().get(0).getReceiveOrgId());
        for (ConsignmentOrder order : orderList.getResult()) {
            //先查出交货单下的明细
            ConsignmentOrderLineLoadListRequest lineLoadListRequest = new ConsignmentOrderLineLoadListRequest();
            lineLoadListRequest.setConsignmentOrderId(order.getId().toString());
            lineLoadListRequest.setLimit(1000);
            Result<List<ConsignmentOrderLine>> listResult = consignmentOrderLineService.loadConsignmentOrderLineList(lineLoadListRequest);
            if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
                continue;
            }
            List<ConsignmentOrderLine> lineList;
            //电商的使用外部行号
            if (isECommerceOrder){
                lineList = listResult.getResult().stream()
                        .filter(x -> StringUtils.isNotBlank(x.getOuterStoLineId()) && StringUtils.isNotBlank(x.getQty()))
                        .collect(Collectors.toList());
            }else {
                lineList = listResult.getResult().stream()
                        .filter(x -> StringUtils.isNotBlank(x.getScItemId()) &&  StringUtils.isNotBlank(x.getQty()))
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(lineList)) {
                continue;
            }
            Map<String, List<ConsignmentOrderLine>> scItemMap;
            //电商调拨单使用外部行号
            if (isECommerceOrder){
                //根据行号聚合交货数量
                scItemMap = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getOuterStoLineId));
                scItemMap.forEach((k, v) -> {
                    if (CollectionUtils.isNotEmpty(v)) {
                        int sum = v.stream().map(ConsignmentOrderLine::getQty).filter(Objects::nonNull)
                                .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                        // 物料 -> 交货累计数量
                        AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
//                        scItemDTO.setScItemId(k);
                        scItemDTO.setOutAllocateOrderLineId(k);
                        scItemDTO.setDeliveryQuantity(sum + "");
                        scItemDTOList.add(scItemDTO);
                    }
                });
            }else {
                scItemMap = lineList.stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getScItemId));
                scItemMap.forEach((k, v) -> {
                    if (CollectionUtils.isNotEmpty(v)) {
                        int sum = v.stream().map(ConsignmentOrderLine::getQty).filter(Objects::nonNull)
                                .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                        // 物料 -> 交货累计数量
                        AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
                        scItemDTO.setScItemId(k);
                        scItemDTO.setDeliveryQuantity(sum + "");
                        scItemDTOList.add(scItemDTO);
                    }
                });
            }
        }
        List<AllocateOrderDeliveryScItemDTO> freshScItemDTOList = Lists.newArrayList();
        //获取到某行/某物料 的交货数量
        if (CollectionUtils.isNotEmpty(scItemDTOList)) {
            Map<String, List<AllocateOrderDeliveryScItemDTO>> collect;
            if (isECommerceOrder){
                collect = scItemDTOList.stream()
                        .collect(Collectors.groupingBy(AllocateOrderDeliveryScItemDTO::getOutAllocateOrderLineId));

            }else {
                collect = scItemDTOList.stream()
                        .collect(Collectors.groupingBy(AllocateOrderDeliveryScItemDTO::getScItemId));
            }
            collect.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    int sum = v.stream().map(AllocateOrderDeliveryScItemDTO::getDeliveryQuantity).filter(Objects::nonNull)
                            .map(x -> x.trim()).mapToInt(y -> InfoUtil.getInt(y.trim())).sum();
                    AllocateOrderDeliveryScItemDTO scItemDTO = new AllocateOrderDeliveryScItemDTO();
                    if (isECommerceOrder){
                        scItemDTO.setOutAllocateOrderLineId(k);
                    }else {
                        scItemDTO.setScItemId(k);
                    }
                    scItemDTO.setDeliveryQuantity(sum + "");
                    freshScItemDTOList.add(scItemDTO);
                }
            });
        }

        //参数 找到了调拨单  调拨物料的集合
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setOutAllocateOrderId(outAllocateOrderId);
        allocateOrderLoadListRequest.setLimit(1000);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return false;
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        if (CollectionUtils.isEmpty(freshScItemDTOList)) {
            return false;
        }
        //添加进货品id 用于后面循环的 暂时用货品编码

        // 交货数量的更新问题, 因为交货单存在删除行的操作 所以要循环现有的明细行 再去匹配交货单的明细行
        AllocateOrderDetailLoadListRequest detailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        detailLoadListRequest.setAllocateOrderId(allocateOrder.getId());
        detailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(detailLoadListRequest);
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
            for (AllocateOrderDetail allocateOrderDetail : result.getResult()) {
                if (allocateOrderDetail == null) {
                    continue;
                }
                //找到符合的货品
                List<AllocateOrderDeliveryScItemDTO> targetList;
                //电商的根据外部行号
                if (isECommerceOrder){
                    targetList = freshScItemDTOList.stream()
                            .filter(x-> Objects.equals(InfoUtil.deleteZeroPrefix(allocateOrderDetail.getOutAllocateOrderLineId()),x.getOutAllocateOrderLineId()))
                            .collect(Collectors.toList());
                }else {
                    targetList = freshScItemDTOList.stream()
                            .filter(x -> Objects.equals(allocateOrderDetail.getScItemId(), x.getScItemId()))
                            .collect(Collectors.toList());
                }
                if (CollectionUtils.isNotEmpty(targetList)) {
                    AllocateOrderDeliveryScItemDTO scItemDTO = targetList.get(0);
                    allocateOrderDetail.setDeliveryQuantity(scItemDTO.getDeliveryQuantity());

                } else {
                    allocateOrderDetail.setDeliveryQuantity("");
                    allocateOrderDetail.setDeliveryDate(new Date(0));
                }
                //防止交货导致收发货数量问题
                allocateOrderDetail.setShipQuantity(null);
                allocateOrderDetail.setReceiveQuantity(null);
                allocateOrderDetail.setShipTime(null);
                allocateOrderDetail.setReceiveTime(null);
                allocateOrderDetail.setStatus(null);
                allocateOrderDetail.setGmt_modified(new Date());
                allocateOrderDetailService.updateAllocateOrderDetail(allocateOrderDetail);

            }
        }
        return true;
    }

    /**
     * 转换成更新预报单的明细数据
     * @param detail 调拨单明细
     * @param oldQuantity 更新前的订单数量
     * @param oldConfirmQuantity 更新前的确认数量
     * @return
     */
    private UpdateAllocateApplyOrderBySapSyncScItemDetail convert2SyncScItemDetail(AllocateOrderDetail detail,
                                                                                   boolean isCreate,
                                                                                   boolean oldClosed,
                                                                                   String closeCode,
                                                                                   String oldQuantity,
                                                                                   String oldConfirmQuantity){
        //转换成同步预报单明细的数据
        UpdateAllocateApplyOrderBySapSyncScItemDetail syncScItemDetail = new UpdateAllocateApplyOrderBySapSyncScItemDetail();
        //是否关闭 关闭原因 编码 货品id
        syncScItemDetail.setCloseCode(closeCode);
        //预报单实际起作用的是closeCode
        syncScItemDetail.setCloseReason(closeCode);
        syncScItemDetail.setClosed(detail.getClose());
        syncScItemDetail.setGoodsId(detail.getScItemId());
        syncScItemDetail.setExpectedProduceDate(detail.getExpectedProduceDate());
        syncScItemDetail.setOldClosed(oldClosed);
        syncScItemDetail.setQuantity(detail.getQuantity());
        syncScItemDetail.setConfirmQuantity(detail.getConfirmQuantity());
        syncScItemDetail.setIsCreate(isCreate);
        syncScItemDetail.setOldQuantity(oldQuantity);
        syncScItemDetail.setOldConfirmQuantity(oldConfirmQuantity);
        //此次调拨单明细更新的差量 (订单数量 确认数量)
        if (oldQuantity == null){
            oldQuantity = BigDecimal.ZERO.toString();
        }
        if (oldConfirmQuantity == null){
            oldConfirmQuantity = BigDecimal.ZERO.toString();
        }
        BigDecimal quantityBigDecimal = StringUtils.isNotBlank(detail.getQuantity()) ? new BigDecimal(detail.getQuantity().trim()) : BigDecimal.ZERO;
        BigDecimal confirmBigDecimal = StringUtils.isNotBlank(detail.getConfirmQuantity()) ? new BigDecimal(detail.getConfirmQuantity().trim())
                : BigDecimal.ZERO;
        syncScItemDetail.setQuantityChange(quantityBigDecimal.subtract(new BigDecimal(oldQuantity)).toString());
        syncScItemDetail.setConfirmQuantityChange(confirmBigDecimal.subtract(new BigDecimal(oldConfirmQuantity)).toString());
        return syncScItemDetail;
    }

    /**
     * 同步回复更新调拨预报单
     * @param allocateApplyOrder
     * @param allocateOrderCode
     * @param syncScItemDetails
     */
    private void syncReplyAllocateApplyOrder(AllocateApplyOrder allocateApplyOrder, String allocateOrderCode,
                                             List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails){
        //调拨单有对应预报单时 更改主子单数据
        if (allocateApplyOrder.getId() != null){
            //更改主单的状态
            //查询预调拨单详情
            UpdateAllocateApplyOrderBySapSyncRequest applyOrderBySapSyncRequest = new UpdateAllocateApplyOrderBySapSyncRequest();
            applyOrderBySapSyncRequest.setAllocateApplyOrderId(allocateApplyOrder.getId());
            //和007更新预报单同一个锁
            applyOrderBySapSyncRequest.setOutAllocateApplyOrderCode(allocateApplyOrder.getOutAllocateApplyOrderId());
            applyOrderBySapSyncRequest.setAllocateOrderCode(allocateOrderCode);
            applyOrderBySapSyncRequest.setSyncScItemDetails(syncScItemDetails);
            //因为是新增就不设置调拨单明细
            allocateApplyOrderWriteRepository.updateByAllocateOrderWithLock(applyOrderBySapSyncRequest);
        }
    }

    //设置信贷信息和状态
    private void fillCreditCheckStatus(AllocateOrder allocateOrder, String creditCheck){
        if (StringUtils.isNotBlank(creditCheck)){
            allocateOrder.setCreditCheck(creditCheck);
            //已冻结订单：
            //信贷检查状态:B冻结、C部分通过
            //未冻结订单：
            //A通过,D冻结后批准
            if (creditCheck.contains(CreditCheck.A.name()) || creditCheck.contains(CreditCheck.D.name())){
                allocateOrder.setCreditCheckStatus(CreditCheckStatus.UNFROZEN_UNCONFIRMED.name());
            }else if (creditCheck.contains(CreditCheck.B.name()) || creditCheck.contains(CreditCheck.C.name())){
                allocateOrder.setCreditCheckStatus(CreditCheckStatus.FROZEN.name());
            }
        }
    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @RepositoryInvoker(printLog = true)
    public AllocateOrderSyncResponse syncAllocateOrder(AllocateOrderSyncRequest allocateOrderSyncRequest) {

        //先检验下参数情况
        AllocateOrderSyncResponse response = new AllocateOrderSyncResponse();
        if (allocateOrderSyncRequest == null) {
            response.setCode("请求参数不能为空");
            return response;
        }
        if (CollectionUtils.isEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            response.setCode("物料不能为空");
            return response;
        }
        List<String> collect = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode())).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            response.setCode("物料不能为空");
            return response;
        }
        //22.04.25 电商调拨单行不能重复
        WmsSDO wmsSDO = InfoUtil.getWmsSDO(allocateOrderSyncRequest.getReceiveAreaId());
        boolean isECommerceOrder = InfoUtil.isECommerceOrder(wmsSDO.getSapSalesOrgId());
        if (isECommerceOrder){
            Set<String> outAllocateOrderLineIdSet = allocateOrderSyncRequest.getAllocateOrderScItemDetails()
                    .stream().map(AllocateOrderScItemDetailDTO::getOutAllocateOrderLineId).collect(Collectors.toSet());
            if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > outAllocateOrderLineIdSet.size()){
                response.setCode("外部调拨单行号不能重复");
                return response;
            }
        }else {
            if (allocateOrderSyncRequest.getAllocateOrderScItemDetails().size() > collect.size()) {
                response.setCode("物料不能重复");
                return response;
            }
        }

        //找出预报单
        AllocateApplyOrder allocateApplyOrder = new AllocateApplyOrder();
        if (!StringUtils.isAllBlank(allocateOrderSyncRequest.getAllocateApplyOrderCode(),
                allocateOrderSyncRequest.getOutAllocateApplyOrderId())) {
            AllocateApplyOrderLoadListRequest applyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getAllocateApplyOrderCode())){
                applyOrderLoadListRequest.setCode(allocateOrderSyncRequest.getAllocateApplyOrderCode());
            }
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getOutAllocateApplyOrderId())){
                applyOrderLoadListRequest.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
            }
            Result<List<AllocateApplyOrder>> applyResult = allocateApplyOrderService.loadAllocateApplyOrderList(applyOrderLoadListRequest);
            if (applyResult != null && CollectionUtils.isNotEmpty(applyResult.getResult())) {
                allocateApplyOrder = applyResult.getResult().get(0);
                log.info("syncAllocateOrder_loadApplyOrder:{}",JSON.toJSONString(applyResult));
                if (AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrder.getStatus())) {
                    response.setCode("预报单是待推送状态,不允许同步");
                    return response;
                }
            }
        }
        AllocateOrderLoadListRequest queryRequest = new AllocateOrderLoadListRequest();
        queryRequest.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
        queryRequest.setCode(allocateOrderSyncRequest.getCode());
        Result<List<AllocateOrder>> queryResult = allocateOrderService.loadAllocateOrderList(queryRequest);
        if (queryResult != null && CollectionUtils.isNotEmpty(queryResult.getResult())) {
            allocateOrderSyncRequest.setCode(queryResult.getResult().get(0).getCode());
        }

        String code = allocateOrderSyncRequest.getCode();
        if (StringUtils.isBlank(code)) {
            AllocateOrderLoadListRequest orderLoadListRequest = new AllocateOrderLoadListRequest();
            orderLoadListRequest.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
            Result<List<AllocateOrder>> orderListResult = allocateOrderService.loadAllocateOrderList(orderLoadListRequest);
            if (orderListResult != null && CollectionUtils.isNotEmpty(orderListResult.getResult())) {
                response.setCode("该外部单号已经存在,不允许新增");
                return response;
            }
            //新增调拨单
            AllocateOrder allocateOrder = JsonUtil.convert(allocateOrderSyncRequest, AllocateOrder.class);
            //代表是常温产品
            allocateOrder.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);

            allocateOrder.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
            allocateOrder.setAllocateApplyOrderId(allocateApplyOrder.getId() == null ? null : allocateApplyOrder.getId() + "");
            allocateOrder.setAllocateApplyOrderCode(StringUtils.isBlank(allocateApplyOrder.getCode()) ? null : allocateApplyOrder.getCode());
            if (allocateApplyOrder.getType() != null) {
                allocateOrder.setType(allocateApplyOrder.getType());
                allocateOrder.setCode(CodeUtil.planCode());
            }else{
                //无前置预报单时,类型一律为仓间调拨单,不存在货场提货单
                log.info("between_warehouse_type");
                allocateOrder.setType(AllocateOrderTypeEnum.BETWEEN_WAREHOUSE.getType());
                allocateOrder.setCode(CodeUtil.betweenCode());
            }
            code = allocateOrder.getCode();
            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司 代码在下面
            allocateOrder.setApplyOrgId(allocateApplyOrder.getHeadquartersOrganizationCode());
            log.info("syncAllocateOrder_applyOrgId:{}",JSON.toJSONString(allocateOrder));
            //如果收货仓不是空的.
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getReceiveAreaId())) {
                allocateOrder.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
            } else {
                allocateOrder.setReceiveAreaId(allocateApplyOrder.getReceiveWarehouseId() == null ? null :
                        allocateApplyOrder.getReceiveWarehouseId() + "");
            }
            allocateOrder.setIsDTC(allocateApplyOrder.getIsDTC() != null && allocateApplyOrder.getIsDTC());
            allocateOrder.setSapSalesOrgId(allocateApplyOrder.getHeadquartersOrganizationCode());
            //如果出入库仓改变的话, 更新一下.
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getShipAreaId());
            allocateOrder.setShipWarehouseId(shipWmsSDO.getWarehouseId());
            allocateOrder.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
            WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(allocateOrder.getReceiveAreaId());
            allocateOrder.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
            allocateOrder.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
            //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
            if (allocateOrder.getApplyOrgId() == null && StringUtils.isNotBlank(allocateOrder.getReceiveOrgId())){
//                GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//                getOrganiztionByIdRequest.setId(allocateOrder.getReceiveOrgId());
//                OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//                if(organiztionById != null){
//                    allocateOrder.setApplyOrgId(organiztionById.getParentId());
//                }
                OrganizationSDO orgSDO = getOrgSDO(allocateOrder.getReceiveOrgId());
                if (orgSDO != null){
                    allocateOrder.setApplyOrgId(orgSDO.getParentId());
                }
            }
            allocateOrder.setConfirmTime(new Date());
            if (allocateOrderSyncRequest.getDocDate() == null) {
                allocateOrder.setDocDate(InfoUtil.docDate());
            } else {
                allocateOrder.setDocDate(allocateOrderSyncRequest.getDocDate());
            }
            //如果是全关闭 那就标记为关闭
//            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
//                boolean allClosed = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
//                        .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
//                if (allClosed) {
//                    allocateOrder.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                } else {
//                    allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                }
//            }
            //TODO 状态
            allocateOrder.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            //成本中心 客户采购参考号 -- 008 更新时 客户成本中心不传递 客户采购参考号
            allocateOrder.setSapCostCenter(allocateApplyOrder.getSapCostCenter());
            allocateOrder.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
            Date expectedDeliveryDate = Nullable.stream(allocateOrderSyncRequest.getAllocateOrderScItemDetails()).map(AllocateOrderScItemDetailDTO::getExpectedDeliveryDate)
                    .findFirst().orElse(null);
            if (expectedDeliveryDate != null){
                allocateOrder.setExpectedDeliveryDate(expectedDeliveryDate);
            }else {
                allocateOrder.setExpectedDeliveryDate(allocateApplyOrder.getHopeDeliveryTime());
            }
            //2024.01.07 新增货场仓
            allocateOrder.setTransferWarehouseId(allocateOrderSyncRequest.getTransferWarehouseId());
            allocateOrder.setAutoFulfillment(Boolean.TRUE.equals(allocateOrderSyncRequest.getAutoFulfillment()));
            allocateOrder.setFulfillmentTypeCode(allocateOrderSyncRequest.getFulfillmentTypeCode());
            // SAP来的系统来源和业态先写死. 因为计划调拨单的数据隔离,现在改成APP_OMNI
            allocateOrder.setFromSys("APP_OMNI");
            allocateOrder.setBusinessType("11");
            allocateOrder.setPriority(1);//默认优先级
            //创建人
            if (PIRFCUSER.equals(allocateOrderSyncRequest.getCreator())){
                allocateOrder.setCreator("system");
                allocateOrder.setUpdater("system");
            }else {
                String creator = Optional.ofNullable(getEmployeeName(allocateOrderSyncRequest.getCreator())).orElse(allocateOrderSyncRequest.getCreator());
                allocateOrder.setCreatorName(creator);
                allocateOrder.setModifierName(creator);
            }
            Map<String, String> bizFeaturesMap = FeatureUtil.fromString(allocateOrder.getBizFeatures());
            if (StringUtils.isNotBlank(allocateApplyOrder.getBizFeatures())){
                Map<String, String> applyBizFeaturesMap = FeatureUtil.fromString(allocateApplyOrder.getBizFeatures());
                if (StringUtils.isNotBlank(applyBizFeaturesMap.get(FeaturesKey.ORDER_TAG))){
                    bizFeaturesMap.put(FeaturesKey.ORDER_TAG,applyBizFeaturesMap.get(FeaturesKey.ORDER_TAG));
                    //标准字段也赋值一下
                    allocateOrder.setOrderTag(applyBizFeaturesMap.get(FeaturesKey.ORDER_TAG));
                }
                if (StringUtils.isNotBlank(applyBizFeaturesMap.get(FeaturesKey.BIZ_UNIT))){
                    bizFeaturesMap.put(FeaturesKey.BIZ_UNIT,applyBizFeaturesMap.get(FeaturesKey.BIZ_UNIT));
                }
            }
            if (MapUtils.isNotEmpty(bizFeaturesMap)){
                allocateOrder.setBizFeatures(FeatureUtil.toString(bizFeaturesMap));
            }

            log.info("syncAllocateOrder_createAllocateOrder:{}",JSON.toJSONString(allocateOrder));
            CreateAllocateOrderResponse createAllocateOrderResponse = allocateOrderService.createAllocateOrder(allocateOrder);
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                int i = 1;
                //用来更新
                List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
                for (AllocateOrderScItemDetailDTO scItemDetail : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
                    AllocateOrderDetail detail = JsonUtil.convert(scItemDetail, AllocateOrderDetail.class);
                    detail.setAllocateOrderCode(code);
                    detail.setAllocateOrderId(createAllocateOrderResponse.getLastInsertId());
                    detail.setType(allocateOrder.getType());
                    detail.setAllocateApplyOrderLineId(scItemDetail.getAllocateApplyOrderLineId());
                    //商品转换 需要把sap的转换成我们的
                    String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetail.getScItemCode());
                    //如果货品查询失败返回
                    if (StringUtils.isBlank(scItemId)){
                        log.error("AllocateOrderWriteRepositoryImpl_passiveSync_queryScItemIdError:{},request:{}",scItemDetail.getScItemCode(),JSON.toJSONString(allocateOrderSyncRequest));
                        response.setCode(scItemDetail.getScItemCode() +"货品查询不存在");
                        return response;
                    }
//                    detail.setScItemId(InfoUtil.deleteZeroPrefix(scItemDetail.getScItemCode()));
                    detail.setScItemId(scItemId);
//                    detail.setScItemCode(InfoUtil.deleteZeroPrefix(scItemDetail.getScItemCode()));
                    detail.setScItemCode(InfoUtil.subStringScItmCode(scItemDetail.getScItemCode()));
                    detail.setClose(scItemDetail.getClosed());
//                    detail.setStatus(Objects.equals(scItemDetail.getClosed(), Boolean.TRUE) ?
//                            AllocateOrderStatus.CLOSED.getValue() : AllocateOrderStatus.Shipment_Processing.getValue());
                    detail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                    detail.setProductGroup(SC_ITEM_PRODUCT_GROUP_CODE);
                    detail.setReturnOrder(allocateOrder.getReturnOrder());
                    detail.setLineNo(i);
                    detail.setQuantity(InfoUtil.trim(detail.getQuantity()));
                    detail.setPrice(InfoUtil.trim(detail.getPrice()));
//                    handleConfirmTime(detail, scItemDetail);
                    detail.setConfirmTime(scItemDetail.getConfirmTime());
                    detail.setConfirmQuantity(InfoUtil.trim(scItemDetail.getConfirmQuantity()));
                    detail.setDiscountAmount(InfoUtil.trim(scItemDetail.getSubTotalAmount()));
                    detail.setSubTotalAmount(InfoUtil.trim(scItemDetail.getSubTotalAmount()));
                    //创建人 修改人
                    detail.setCreatorName(allocateOrder.getCreatorName());
                    detail.setModifierName(allocateOrder.getModifierName());
                    //子单扩展信息
                    Map<String, String> subBizFeaturesMap = FeatureUtil.fromString(detail.getBizFeatures());
                    subBizFeaturesMap.put(FeaturesKey.RECEIVE_AREA_ID,allocateOrder.getReceiveAreaId());
                    detail.setBizFeatures(FeatureUtil.toString(subBizFeaturesMap));
                    allocateOrderDetailService.createAllocateOrderDetail(detail);
                    i++;
                    // 操作 预报单部分 回复数量 关闭状态 生产日期
                    //组装同步更新预报单的明细数据
                    syncScItemDetails.add(convert2SyncScItemDetail(detail,true,false,
                            scItemDetail.getCloseCode(), null,null));
                }
                //更改预报单主子单状态,回复数量 拒接原因...
                syncReplyAllocateApplyOrder(allocateApplyOrder,allocateOrder.getCode(),syncScItemDetails);
            }
//            delivery(allocateOrderSyncRequest.getOutAllocateOrderId());
            response.setCode(code);
            return response;
        }
        //下面是更新操作的操作
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setCode(allocateOrderSyncRequest.getCode());
        Result<List<AllocateOrder>> orderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (orderList == null || CollectionUtils.isEmpty(orderList.getResult())) {
            response.setCode("未查询到该调拨单号");
            return response;
        }

        AllocateOrder order = orderList.getResult().get(0);
        //如果

//        if (!Objects.equals(order.getOutAllocateOrderId(),allocateOrderSyncRequest.getOutAllocateOrderId())){
//            response.setCode("调拨单号和外部调拨单号关系不匹配");
//            return response;
//        }
        //如果是008传递过来是待推送,我们就直接先改成待发货状态
        if (Objects.equals(order.getStatus(), AllocateOrderStatus.WAIT_PUSH.getValue())) {
            order.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
            if (StringUtils.isNotBlank(allocateOrderSyncRequest.getOutAllocateOrderId())){
                order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
            }
            allocateOrderService.updateAllocateOrder(order);
            AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
            allocateOrderDetailLoadListRequest.setAllocateOrderId(order.getId());
            allocateOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
                for (AllocateOrderDetail detail : result.getResult()) {
                    //如果是待推送状态,就修改子单明细的状态
                    if (AllocateOrderStatus.WAIT_PUSH.getValue().equals(detail.getStatus())){
                        detail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
                        allocateOrderDetailService.updateAllocateOrderDetail(detail);
                    }
                }
            }
//            response.setCode("调拨单未推送成功或回调失败,不允许更新");
//            return response;
        }


        AllocateOrderDetailLoadListRequest checkRequest = new AllocateOrderDetailLoadListRequest();
        checkRequest.setAllocateOrderId(order.getId());
        checkRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrderDetail>> checkResult = allocateOrderDetailService.loadAllocateOrderDetailList(checkRequest);
        if (checkResult != null && CollectionUtils.isNotEmpty(checkResult.getResult()) && !isECommerceOrder) {
            //找出现有的明细; 如果传递的商品有新增的.
            if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
                List<String> scItemCodes = checkResult.getResult().stream()
                        .filter(y -> StringUtils.isNotBlank(y.getScItemCode()))
                        .map(x -> InfoUtil.subStringScItmCode(x.getScItemCode()))
                        .distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(scItemCodes)) {
                    List<String> list = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
                            .map(z -> InfoUtil.subStringScItmCode(z.getScItemCode())).collect(Collectors.toList());
                    boolean b = scItemCodes.stream().anyMatch(x -> !list.contains(x));
                    if (b) {
                        response.setCode("物料编码不允许修改");
                        return response;
                    }
                }
            }
        }


        order.setOutAllocateOrderId(allocateOrderSyncRequest.getOutAllocateOrderId());
        order.setOutAllocateApplyOrderId(allocateOrderSyncRequest.getOutAllocateApplyOrderId());
        order.setTypeCard(allocateOrderSyncRequest.getTypeCard());
        order.setSapChannel(allocateOrderSyncRequest.getSapChannel());
        order.setProductGroup(allocateOrderSyncRequest.getProductGroup());
        order.setShipAreaId(allocateOrderSyncRequest.getShipAreaId());
        order.setShipWarehouseId(allocateOrderSyncRequest.getShipWarehouseId());
        //如果有收货仓改变
        if (StringUtils.isNotBlank(allocateOrderSyncRequest.getReceiveAreaId())) {
            order.setReceiveAreaId(allocateOrderSyncRequest.getReceiveAreaId());
        }
        order.setReceiveWarehouseId(allocateOrderSyncRequest.getReceiveWarehouseId());
        order.setCreateTime(allocateOrderSyncRequest.getCreateTime());
        order.setShipMethod(allocateOrderSyncRequest.getShipMethod());
        order.setReturnOrder(allocateOrderSyncRequest.getReturnOrder());
        order.setFeatures(allocateOrderSyncRequest.getFeatures());
        order.setRemark(allocateOrderSyncRequest.getRemark());
        //如果出入库仓改变的话, 更新一下.
        WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(order.getShipAreaId());
        order.setShipWarehouseId(shipWmsSDO.getWarehouseId());
        order.setShipOrgId(shipWmsSDO.getSapSalesOrgId());
        WmsSDO receiveWmsSDO = InfoUtil.getWmsSDO(order.getReceiveAreaId());
        order.setReceiveWarehouseId(receiveWmsSDO.getWarehouseId());
        order.setReceiveOrgId(receiveWmsSDO.getSapSalesOrgId());
        if (allocateOrderSyncRequest.getDocDate() == null) {
            order.setDocDate(InfoUtil.docDate());
        } else {
            order.setDocDate(allocateOrderSyncRequest.getDocDate());
        }
        order.setGmt_modified(new Date());
        //提报组织id 如果有预报单选择预报单的, sap直接创建的  取收货逻辑仓库-》销售组织-〉所属公司
        if (order.getApplyOrgId() == null && StringUtils.isNotBlank(order.getReceiveOrgId())){
//            GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//            getOrganiztionByIdRequest.setId(order.getReceiveOrgId());
//            OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//            if(organiztionById != null){
//                order.setApplyOrgId(organiztionById.getParentId());
//            }
            OrganizationSDO orgSDO = getOrgSDO(order.getReceiveOrgId());
            if (orgSDO != null){
                order.setApplyOrgId(orgSDO.getParentId());
            }
        }
//        order.setApplyOrgId(allocateApplyOrder.getApplyOrgId() == null ? null : allocateApplyOrder.getApplyOrgId() + "");
//        if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
//            boolean allClosed = allocateOrderSyncRequest.getAllocateOrderScItemDetails().stream()
//                    .allMatch(x -> Objects.equals(Boolean.TRUE, x.getClosed()));
//            if (allClosed) {
//                order.setStatus(AllocateOrderStatus.CLOSED.getValue());
//            } else {
//                if (order.getStatus() == null) {
//                    order.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                }
//            }
//        }
        // 参考号 和成本中心
        order.setSapRefPoNo(allocateApplyOrder.getSapRefPoNo());
        order.setSapCostCenter(allocateApplyOrder.getSapCostCenter());
        Date expectedDeliveryDate = Nullable.stream(allocateOrderSyncRequest.getAllocateOrderScItemDetails()).map(AllocateOrderScItemDetailDTO::getExpectedDeliveryDate)
                .findFirst().orElse(null);
        if (expectedDeliveryDate != null){
            order.setExpectedDeliveryDate(expectedDeliveryDate);
        }
        if (StringUtils.isBlank(order.getAllocateApplyOrderId()) && allocateApplyOrder.getId() != null){
            order.setAllocateApplyOrderId(allocateApplyOrder.getId().toString());
        }
        if (StringUtils.isBlank(order.getAllocateApplyOrderCode()) && StringUtils.isNotBlank(allocateApplyOrder.getCode())){
            order.setAllocateApplyOrderCode(allocateApplyOrder.getCode());
        }
        //这里修正008的更新人字段 默认
        if (StringUtils.isNotBlank(allocateOrderSyncRequest.getLastUpdateUser()) && !PIRFCUSER.equals(allocateOrderSyncRequest.getLastUpdateUser())){
            order.setModifierName(Optional.ofNullable(getEmployeeName(allocateOrderSyncRequest.getLastUpdateUser())).orElse(allocateOrderSyncRequest.getLastUpdateUser()));
        }
        allocateOrderService.updateAllocateOrder(order);

//        //查询履约单
//        SearchFulfullmentOrderReq searchFulfullmentOrderReq = new SearchFulfullmentOrderReq();
//        searchFulfullmentOrderReq.setSourceOrderNo(order.getCode());
//        searchFulfullmentOrderReq.setFulfillmentDirectionType(FulfillmentDirectionTypeEnum.FORWARD.getValue());
//        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> searchFulfillmentOrder = fulfillmentOrderAbilityService.searchFulfullmentOrder(searchFulfullmentOrderReq);
//        log.info("syncAllocateOrder_searchFulfillmentOrder_result:{}",JSON.toJSONString(searchFulfillmentOrder));
//        List<FulfillmentGetRes> fulfillmentGetResList = Optional.ofNullable(searchFulfillmentOrder)
//                .map(com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result::getResult)
//                .orElse(Lists.newArrayList());

        //查询出出库单
        WmsOrderQueryRequest wmsOrderQueryRequest = new WmsOrderQueryRequest();
        wmsOrderQueryRequest.setBizOrderId(order.getCode());
        wmsOrderQueryRequest.setContainSubOrders(true);
        com.alibaba.cz.base.tool.result.Result<WarehousingOrdersQueryResponse> wmsQueryResult = warehousingOrderReadService.queryWmsOrderByOtherOrder(wmsOrderQueryRequest);
        log.info("AllocateOrderWriteServiceImpl_syncAllocateOrder_queryWmsResult:{}",JSON.toJSONString(wmsQueryResult));
        List<WarehousingOrderDTO> warehousingOrderDTOList = Optional.ofNullable(wmsQueryResult).map(com.alibaba.cz.base.tool.result.Result::getResult)
                .map(WarehousingOrdersQueryResponse::getWarehousingOrders).orElse(Lists.newArrayList());

        if (CollectionUtils.isNotEmpty(allocateOrderSyncRequest.getAllocateOrderScItemDetails())) {
            //获取最大的行号
            AllocateOrderDetailLoadListRequest request = new AllocateOrderDetailLoadListRequest();
            request.setAllocateOrderCode(code);
            request.setLimit(MAX_PAGE_SIZE);
            Result<List<AllocateOrderDetail>> rr = allocateOrderDetailService.loadAllocateOrderDetailList(request);
            int line = 1;
            if (rr != null && CollectionUtils.isNotEmpty(rr.getResult())) {
//                String lines = rr.getResult().stream().filter(Objects::nonNull).filter(orderDetail -> StringUtils.isNotBlank(orderDetail.getLineNo()))
//                        .max(Comparator.comparing(AllocateOrderDetail::getLineNo)).get().getLineNo();
//                if (StringUtils.isNotBlank(lines))line = Integer.parseInt(lines);
                List<Integer> lineList = rr.getResult().stream().filter(Objects::nonNull).map(AllocateOrderDetail::getLineNo)
                        .filter(lineNo -> lineNo != null).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(lineList)) {
                    Integer max = Collections.max(lineList);
                    if (max != null) {
                        line = max;
                    }
                }

            }
            List<UpdateAllocateApplyOrderBySapSyncScItemDetail> syncScItemDetails = Lists.newArrayList();
            for (AllocateOrderScItemDetailDTO scItemDetailDTO : allocateOrderSyncRequest.getAllocateOrderScItemDetails()) {
                AllocateOrderDetailLoadListRequest listRequest = new AllocateOrderDetailLoadListRequest();
                listRequest.setAllocateOrderCode(code);
//                listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
                //008赋值的是scItemCode
                String scItemId = InfoUtil.getScItemIdByOutCode(scItemDetailDTO.getScItemCode());
                if (StringUtils.isBlank(scItemId)){
                    log.error("AllocateOrderWriteRepositoryImpl_passiveSync_queryScItemIdError:{},request:{}",scItemDetailDTO.getScItemCode(),JSON.toJSONString(allocateOrderSyncRequest));
                    response.setCode(scItemDetailDTO.getScItemCode() +"货品查询不存在");
                    return response;
                }
                listRequest.setScItemId(scItemId);
                //22.04.25 电商调拨单使用外部行号镜像匹配
                if (isECommerceOrder){
                    listRequest.setScItemId(null);
                    listRequest.setOutAllocateOrderLineId(scItemDetailDTO.getOutAllocateOrderLineId());
                }
                //定义一个 原始量
                String oldQuantity = null;
                boolean oldAllocateClosed=false;
                String oldConfirmQuantity = null;
                Result<List<AllocateOrderDetail>> result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
                //2022.07.21 如果根据外部行号查不到 那就再根据行号查询一下
                if (isECommerceOrder){
                    if (result == null || CollectionUtils.isEmpty(result.getResult()) && StringUtils.isNotBlank(scItemDetailDTO.getLineNo())){
                        listRequest.setScItemId(null);
                        listRequest.setOutAllocateOrderLineId(null);
                        listRequest.setLineNo(Integer.valueOf(scItemDetailDTO.getLineNo()));
                        result = allocateOrderDetailService.loadAllocateOrderDetailList(listRequest);
                    }
                }
                if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                    //更新货品
                    AllocateOrderDetail orderDetail = result.getResult().get(0);
                    oldQuantity = orderDetail.getQuantity();
                    oldAllocateClosed= orderDetail.getClose() != null && orderDetail.getClose();
                    oldConfirmQuantity = orderDetail.getConfirmQuantity();

                    convert(orderDetail, scItemDetailDTO);
                    //得到该行对应履约单明细下的所有明细1数量 ,过滤出调拨单所关联的所有履约单所关联的所有出库单明细1
                    BigDecimal sumQuantity = Nullable.stream(warehousingOrderDTOList).map(WarehousingOrderDTO::getWmsOrderDetailList)
                            .filter(CollectionUtils::isNotEmpty).flatMap(Collection::stream)
                            .filter(Objects::nonNull).filter(wmsOrderDetailDTO -> Objects.equals(wmsOrderDetailDTO.getBizSubOrderId(), orderDetail.getLineNo() == null ? null : orderDetail.getLineNo().toString()))
                            .map(WmsOrderDetailDTO::getGoodsQuantity)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::new)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    log.info("syncAllocateOrder_update_sumQuantity:{},lineNo:{}",sumQuantity,orderDetail.getLineNo());
                    if (Boolean.TRUE.equals(allocateOrderSyncRequest.getReturnOrder())){
                        BigDecimal confirmQuantity = StringUtils.isBlank(scItemDetailDTO.getQuantity()) ? BigDecimal.ZERO : new BigDecimal(scItemDetailDTO.getQuantity().trim());
                        if (confirmQuantity.compareTo(sumQuantity) < 0){
                            log.info("syncAllocateOrder_less_than,sapConfirmQuantity:{},sumQuantity:{}",scItemDetailDTO.getQuantity(),sumQuantity);
                            orderDetail.setQuantity(oldQuantity);
                            orderDetail.setConfirmQuantity(oldConfirmQuantity);
                        }
                    }else {
                        BigDecimal confirmQuantity = StringUtils.isBlank(scItemDetailDTO.getConfirmQuantity()) ? BigDecimal.ZERO : new BigDecimal(scItemDetailDTO.getConfirmQuantity().trim());
                        if (confirmQuantity.compareTo(sumQuantity) < 0){
                            log.info("syncAllocateOrder_less_than,sapConfirmQuantity:{},sumQuantity:{}",scItemDetailDTO.getConfirmQuantity(),sumQuantity);
                            orderDetail.setQuantity(oldQuantity);
                            orderDetail.setConfirmQuantity(oldConfirmQuantity);
                        }
                    }
                    orderDetail.setScItemId(scItemId);
                    orderDetail.setProductGroup(allocateOrderSyncRequest.getProductGroup());
//                    orderDetail.setConfirmTime(new Date());
                    handleConfirmTime(orderDetail, scItemDetailDTO);
                    orderDetail.setGmt_modified(new Date());
                    orderDetail.setDiscountAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    //行备注问题
                    orderDetail.setRemarks(scItemDetailDTO.getFeatures());
//                    if (Objects.equals(scItemDetailDTO.getClosed(), Boolean.TRUE)) {
//                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                    } else if (Objects.equals(orderDetail.getStatus(), AllocateOrderStatus.CLOSED.getValue())) {
//                        orderDetail.setStatus(AllocateOrderStatus.Shipment_Processing.getValue());
//                    }
                    //再次判断下状态 收货 发货的行状态
//                    sapUpdateLineStatus(orderDetail);
                    if (StringUtils.isNotBlank(allocateOrderSyncRequest.getLastUpdateUser()) && !PIRFCUSER.equals(allocateOrderSyncRequest.getLastUpdateUser())){
                        orderDetail.setModifierName(order.getModifierName());
                    }
                    allocateOrderDetailService.updateAllocateOrderDetail(orderDetail);
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,false,oldAllocateClosed,
                            orderDetail.getCloseCode(), oldQuantity,oldConfirmQuantity));
                } else {
                    AllocateOrderDetail orderDetail = new AllocateOrderDetail();
                    convert(orderDetail, scItemDetailDTO);
                    orderDetail.setScItemId(scItemId);
                    //获取主单的type
                    orderDetail.setType(order.getType());
                    orderDetail.setAllocateOrderCode(code);
                    orderDetail.setAllocateOrderId(order.getId());
                    orderDetail.setLineNo(line + 1);
                    orderDetail.setProductGroup(allocateOrderSyncRequest.getProductGroup());
//                    orderDetail.setConfirmTime(new Date());
                    handleConfirmTime(orderDetail, scItemDetailDTO);
                    orderDetail.setGmt_modified(new Date());
                    orderDetail.setDiscountAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
                    orderDetail.setSubTotalAmount(InfoUtil.trim(scItemDetailDTO.getSubTotalAmount()));
//                    if (Objects.equals(scItemDetailDTO.getClosed(), Boolean.TRUE)) {
//                        orderDetail.setStatus(AllocateOrderStatus.CLOSED.getValue());
//                    }
                    orderDetail.setCreatorName(order.getModifierName());
                    orderDetail.setModifierName(order.getModifierName());

                    allocateOrderDetailService.createAllocateOrderDetail(orderDetail);
                    line++;
                    syncScItemDetails.add(convert2SyncScItemDetail(orderDetail,true,false,
                            orderDetail.getCloseCode(),null,null));
                }
                //更新一下主单状态..
                AllocateOrderDetailLoadListRequest endQuery = new AllocateOrderDetailLoadListRequest();
                endQuery.setAllocateOrderId(order.getId());
                endQuery.setLimit(MAX_PAGE_SIZE);
                Result<List<AllocateOrderDetail>> endList = allocateOrderDetailService.loadAllocateOrderDetailList(endQuery);
//                sapUpdateOrderStatus(endList, order);
            }
            //同步回复更新预报单的主子单信
            syncReplyAllocateApplyOrder(allocateApplyOrder,order.getCode(),syncScItemDetails);
        }
        updateAllocateApplyOrderLineId(order.getCode(), allocateApplyOrder.getId());
        response.setCode(code);

        return response;
    }

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Object batchCloseAllocateOrderDetail(BatchCloseRequest batchCloseRequest) {
        return allocateOrderDetailService.batchClose(batchCloseRequest);
    }

    /**
     * 调拨预报单交货
     * @param request
     */
    @Override
    public void deliveredAllocateApplyOrder(AllocateApplyOrderDeliveredRequest request) {
        log.info("deliveredAllocateApplyOrder_request:{}",JSON.toJSONString(request));
        if (request.getAllocateApplyOrderId() == null){
            return;
        }
        AllocateApplyOrderDetailLoadListRequest allocateApplyOrderDetailLoadListRequest = new AllocateApplyOrderDetailLoadListRequest();
        allocateApplyOrderDetailLoadListRequest.setAllocateApplyOrderId(request.getAllocateApplyOrderId().intValue());
        allocateApplyOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateApplyOrderDetail>> applyOrderDetailList = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(allocateApplyOrderDetailLoadListRequest);
        if (applyOrderDetailList == null || CollectionUtils.isEmpty(applyOrderDetailList.getResult())){
            log.error("deliveredAllocateApplyOrder_not_match_detail");
            return;
        }
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setAllocateApplyOrderId(request.getAllocateApplyOrderId().toString());
        allocateOrderLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            log.error("deliveredAllocateApplyOrder_not_match_apply_order_detail");
            return;
        }
        QueryListByIdsRequest queryListByIdsRequest = new QueryListByIdsRequest();
        queryListByIdsRequest.setAllocateOrderIds(listResult.getResult().stream().map(AllocateOrder::getId).collect(Collectors.toList()));
        queryListByIdsRequest.setLimit(MAX_PAGE_SIZE);
        QueryListByIdsResponse queryListByIdsResponse = allocateOrderDetailService.queryListByIds(queryListByIdsRequest);
        if (queryListByIdsResponse == null || CollectionUtils.isEmpty(queryListByIdsResponse.getResult())){
            log.error("deliveredAllocateApplyOrder_not_match_allocate_order_detail");
            return;
        }
        List<AllocateOrderDetail> allocateOrderDetailList = queryListByIdsResponse.getResult();
        log.info("deliveredAllocateApplyOrder_allocateOrderDetailList:{}",JSON.toJSONString(allocateOrderDetailList));
        //构建一个更新入参
        applyOrderDetailList.getResult().forEach(allocateApplyOrderDetail -> {
            BigDecimal deliveryQuantity = allocateOrderDetailList.stream().filter(allocateOrderDetail ->
                            Objects.equals(InfoUtil.deleteZeroPrefix(allocateApplyOrderDetail.getOutLineNo()), InfoUtil.deleteZeroPrefix(allocateOrderDetail.getOutAllocateApplyOrderLineId())))
                    .map(AllocateOrderDetail::getDeliveryQuantity).filter(StringUtils::isNotBlank)
                    .map(String::trim).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
            String bizFeatures = allocateApplyOrderDetail.getBizFeatures();
            Map<String, String> bizFeaturesMap = FeatureUtil.fromString(bizFeatures);
            bizFeaturesMap.put(FeaturesKey.CUMULATIVE_CONSIGNMENT_QUANTITY,deliveryQuantity.toString());
            UpdateFeaturesRequest updateFeaturesRequest = UpdateFeaturesRequest.builder().
                    mainOrderId(allocateApplyOrderDetail.getAllocateApplyOrderId().toString())
                    .lineNo(allocateApplyOrderDetail.getLineNo())
                    .bizFeatures(FeatureUtil.toString(bizFeaturesMap))
                    .build();
            log.info("deliveredAllocateApplyOrder_updateFeatures:{}",JSON.toJSONString(updateFeaturesRequest));
            allocateApplyOrderDetailService.updateFeatures(updateFeaturesRequest);
        });
    }

    /**
     * 根据工号获取姓名
     * @param workId
     * @return
     */
    private String getEmployeeName(String workId){
        if (StringUtils.isBlank(workId)){
            return null;
        }
        com.alibaba.cz.base.tool.result.Result<List<EmployeeResponse>> employees = employeeService.getEmployeesByWorkId(workId);
        log.info("syncAllocateOrder_getEmployeesByWorkId:{}",JSON.toJSONString(employees));
        if (employees != null && CollectionUtils.isNotEmpty(employees.getResult())){
            return Optional.ofNullable(employees.getResult().get(0)).map(EmployeeResponse::getEmployeeSDO).map(EmployeeSDO::getName).orElse(null);
        }
        return null;
    }
}
